【问题标题】:TypeError Cannot read property 'map' of undefined when getting data from Api从 Api 获取数据时,TypeError 无法读取未定义的属性“地图”
【发布时间】:2020-06-20 21:02:08
【问题描述】:

我正在尝试使用 React 从 API 获取一些数据。以下是我收到错误的组件之一。

import React, { Component } from "react";
import Filmcard from "./Filmcard";

const url = "http://www.omdbapi.com/?s=star&apikey=4ababda2";

class Filmcardlist extends Component {
  constructor() {
    super();
    this.state = {
      films: []
    };
  }
  componentDidMount() {
    fetch(url)
      .then(resonse => resonse.json())
      .then(data => {
        this.setState({ films: data });
      })
      .catch(error => console.log("I have errored" + error));
  }

  render() {
    return (
      <div>
        {this.props.films.map(film => (
          <Filmcard
            Title={film.Title}
            Year={film.Year}
            imdbID={film.imdbID}
            Type={film.Type}
          />
        ))}
      </div>
    );
  }
}

export default Filmcardlist;

我对 React 还很陌生,我不知道为什么会出现这个错误。

【问题讨论】:

    标签: javascript reactjs api


    【解决方案1】:

    改变:

    this.setState({ films: data });
    

    到:

    this.setState({ films: data.Search });
    

    this.props.filmsthis.state.films 在渲染函数中。

    【讨论】:

    • 不幸的是,这并没有渲染任何东西,也没有任何东西出现在胶片阵列上。
    • 你确定data中有有效的数组来自获取响应吗?
    • 在 JSON 响应中有一个名为“Search”的数组。我已将 {films: data} 更改为 {films: Search} 。这不起作用。它是说搜索未定义。
    • 响应是对象中的嵌套数组。
    • 不幸的是,它没有返回任何东西。
    【解决方案2】:

    只需使用 state 更改道具,当我阅读 cmets 时,您需要映射 data.search。 试试这个代码,希望能帮到你!

    {
    if(this.state && this.state.films && this.state.films.search){
    this.state.films.search.map(film => (
          <Filmcard
            Title={film.Title}
            Year={film.Year}
            imdbID={film.imdbID}
            Type={film.Type}
          />
        ))}
    }
    

    【讨论】:

    • 不幸的是,这给了我这一行的语法错误if (this.state &amp;&amp; this.state.films &amp;&amp; this.state.films.search)
    猜你喜欢
    • 2021-12-20
    • 2021-07-13
    • 1970-01-01
    • 2021-11-09
    • 2019-12-12
    • 2021-06-25
    • 1970-01-01
    • 2022-01-12
    • 2022-01-14
    相关资源
    最近更新 更多