反应TypeError:items.map不是函数componentDidMount / <this.setState({

时间:2018-11-19 12:00:08

标签: reactjs rest

我有愚蠢的错误。

比起我,我尝试使用以下网址: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 / < src / App.js:27

  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不是函数,所以我使用prevouse URL没关系。我想通过新的REST API网址创建搜索。

1 个答案:

答案 0 :(得分: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 ...
  ]
}