简体   繁体   中英

TypeError Cannot read property 'map' of undefined when getting data from Api

I am trying to get get some data from an API using React. Below is one of my components where I am getting the error.

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;

I am fairly new to React and I'm not sure why I am getting this error.

change:

this.setState({ films: data });

to:

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

and this.props.films to this.state.films in render function.

Just change props with state and as I read the comments you need to map data.search. Try this code, hope I helped!

{
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}
      />
    ))}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM