当我使用这个组件时,我得到以下错误。当我只对另一个API使用完全相同的函数时,它工作了,我得到了API的输出。
TypeError:物品。Map不是函数ApiInfo.renderC:/用户/32479/mikiesoftMovies2/cinemaReact-master/src/组件/ApiInfo.js: 35
32 | 33 | return ( 34 | <div className = "App"> 35 | <h1> Fetch data from an api in react </h1> { | ^ 36 | items.map((item) => ( 37 | <ol key = { item.id } > 38 | Title: { item.original_title }
当我用另一个API尝试它时,它工作了,我没有任何错误。我是React的新手,所以我不知道哪里出错了。
这是我的代码(与API,给我的错误),它只是一个代码,从API请求信息,并把它放在一个ol
:
import React from "react";
export class ApiInfo extends React.Component {
// Constructor
constructor(props) {
super(props);
this.state = {
items: [],
DataisLoaded: false
};
}
// ComponentDidMount is used to
// execute the code
componentDidMount() {
fetch(
"https://api.themoviedb.org/3/movie/top_rated?api_key=55957fcf3ba81b137f8fc01ac5a31fb5&language=en-US&page=1")
.then((res) => res.json())
.then((res) => {
this.setState({
items: res,
DataisLoaded: true
});
})
}
render() {
const { DataisLoaded, items } = this.state;
if (!DataisLoaded) return <div>
<h1> Please wait some time.... </h1> </div> ;
return (
<div className = "App">
<h1> Fetch data from an api in react </h1> {
items.map((item) => (
<ol key = { item.id } >
Title: { item.original_title }
</ol>
))
}
</div>
);
}
}
export default ApiInfo;
和我将添加一个json的例子从我正在使用的API:来自API的未定义的json
您正在查找的电影项目由res.results
中的电影数据库API返回,而不是在res
中:
this.setState({
items: res.results,
DataisLoaded: true
});
请参阅API参考
作为一个旁注,处理HTTP错误情况是一个很好的实践,所以考虑在你的fetch调用中添加一个catch块。
变量items
不是数组。因此,map
不是一个函数。输出变量res
,您将看到隐藏在后面的内容以及必须分配给items
的内容。