【问题标题】:React TypeError: items.map is not a function componentDidMount/< this.setState({React TypeError: items.map 不是函数 componentDidMount/< this.setState({
【发布时间】:2019-04-21 18:52:52
【问题描述】:

我犯了一个愚蠢的错误。

比我尝试使用这个网址:https://api.unsplash.com/photos?client_id=...&page=1 没关系

比我尝试使用这个网址:https://api.unsplash.com/search/photos?client_id=...&page=1&query=office 失败了:

TypeError: items.map 不是函数 使成为 src/App.js:51

  48 |   </div>
  49 | </nav>
  50 | 
> 51 | <div className="row container text-center">
     | ^  52 | {items.map(item => (

componentDidMount/

  24 | fetch('https://api.unsplash.com/search/photos?client_id=ce566471febd4bbaa975c83517a1d9e74e9fd8f309a104de1f5881b07ee936cc&page=1&query=office')
  25 |     .then(res => res.json())
  26 |     .then(json => {
> 27 |         this.setState({
     | ^  28 |             isLoaded: true,

我的 App.js 代码:

import React, { Component } from 'react';
import fetch from 'isomorphic-fetch'
import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom'

// const Child = ({match}) => (
//     <div>
//       <h1>ID: {match.params.tag}</h1>
//     </div>
//   )

class App extends Component {
  constructor(props) {
        super(props);
        this.state = {
            items: [],
            isLoaded: false
        }
    }
    componentDidMount() {
        fetch('https://api.unsplash.com/search/photos?client_id=...&page=1&query=office')
            .then(res => res.json())
            .then(json => {
                this.setState({
                    isLoaded: true,
                    items: json
                });
            });
    }
  render() {
    var { isLoaded, items } = this.state;
        if (!isLoaded) {
            return "<div>Loading...</div>";
        }
    return (
      <Router>
      <div className="App">
       <nav className="navbar navbar-light bg-light justify-content-between">
        <div className="container">
          <a className="navbar-brand">MediaPark</a>
          <form className="form-inline">
            <input className="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"></input>
            <button className="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
          </form>
          </div>
        </nav>

        <div className="row container text-center">
        {items.map(item => (
          <div className="card col-md-4" key="{item.id}">
              <img class="card-img-top" src={item.urls.thumb} alt="{item.id}"></img>
              <div class="card-body">
                  <h5 class="card-title">{item.id}</h5>
                  <p class="card-text">{item.description}</p>
                  <a href={item.urls.raw} class="btn btn-primary">Full image</a>
              </div>
          </div>
          ))}
        </div>
        
      </div>
      </Router>
    );
  }
}

export default App;

为什么我得到错误 TypeError: items.map is not a function,然后我使用 prevouse URL 就可以了。我想通过新的 REST API url 创建搜索。

【问题讨论】:

  • 在此处记录json 的值:.then(json =&gt; { console.log('json', json); this.setState({ isLoaded: true, items: json }); }); 并检查它应该是一个数组。

标签: reactjs rest


【解决方案1】:

如果您查看 API 文档,您从搜索中返回的数据是如下所示的对象。这意味着您必须在 results 属性上进行映射。你得到一个对象而不是一个数组。 所以如果你只想要结果,它可能会为你做这样的事情:

this.setState({
  isLoaded: true,
  items: json.results
});

https://unsplash.com/documentation

{
  "total": 133,
  "total_pages": 7,
  "results": [
    {
      "id": "eOLpJytrbsQ",
      "created_at": "2014-11-18T14:35:36-05:00",
      "width": 4000,
      "height": 3000,
      "color": "#A7A2A1",
      "likes": 286,
      "liked_by_user": false,
      "description": "A man drinking a coffee.",
      "user": {
        "id": "Ul0QVz12Goo",
        "username": "ugmonk",
        "name": "Jeff Sheldon",
        "first_name": "Jeff",
        "last_name": "Sheldon",
        "instagram_username": "instantgrammer",
        "twitter_username": "ugmonk",
        "portfolio_url": "http://ugmonk.com/",
        "profile_image": {
          "small": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32&s=7cfe3b93750cb0c93e2f7caec08b5a41",
          "medium": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=64&w=64&s=5a9dc749c43ce5bd60870b129a40902f",
          "large": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=128&w=128&s=32085a077889586df88bfbe406692202"
        },
        "links": {
          "self": "https://api.unsplash.com/users/ugmonk",
          "html": "http://unsplash.com/@ugmonk",
          "photos": "https://api.unsplash.com/users/ugmonk/photos",
          "likes": "https://api.unsplash.com/users/ugmonk/likes"
        }
      },
      "current_user_collections": [],
      "urls": {
        "raw": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f",
        "full": "https://hd.unsplash.com/photo-1416339306562-f3d12fefd36f",
        "regular": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&s=92f3e02f63678acc8416d044e189f515",
        "small": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&s=263af33585f9d32af39d165b000845eb",
        "thumb": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&s=8aae34cf35df31a592f0bef16e6342ef"
      },
      "links": {
        "self": "https://api.unsplash.com/photos/eOLpJytrbsQ",
        "html": "http://unsplash.com/photos/eOLpJytrbsQ",
        "download": "http://unsplash.com/photos/eOLpJytrbsQ/download"
      }
    },
    // more photos ...
  ]
}

【讨论】:

    猜你喜欢
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 2019-10-25
    • 2019-08-03
    • 2022-01-25
    • 2018-09-22
    • 1970-01-01
    相关资源
    最近更新 更多