[英]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.我正在尝试使用 React 从 API 获取一些数据。 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.我对 React 相当陌生,我不确定为什么会收到此错误。
change:改变:
this.setState({ films: data });
to:到:
this.setState({ films: data.Search });
and this.props.films
to this.state.films
in render function.和
this.props.films
到this.state.films
在渲染函数中。
Just change props with state and as I read the comments you need to map data.search.只需更改带有状态的道具,当我阅读您需要映射 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}
/>
))}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.