【发布时间】:2018-02-01 20:59:26
【问题描述】:
更新:
顺便说一句,我已经定义了带有响应的数据
setState({ fetchedData: responseJSON.data })
我只是在 setState 中获取名为 fetchedData: [] 的响应数据@我正在获取这些数据
{
"data":{
"title": "The Basics - Networking",
"description": "Your app fetched this from a remote endpoint!",
"movies": [
{ "id": "1", "movieTitle": "Star Wars", …},
{ "id": "2", "movieTitle": "Back to the Future", …}
{ "id": "3", "movieTitle": "The Matrix", …}
{ "id": "4", "movieTitle": "Inception", …},
{ "id": "5", "movieTitle": "Interstellar", …}
]
}
}
另外,如果我为 this.state.fetchedData.movies 进行控制台日志,我会收到回复
[
{ "id": "1", "movieTitle": "Star Wars", …},
{ "id": "2", "movieTitle": "Back to the Future", …}
{ "id": "3", "movieTitle": "The Matrix", …}
{ "id": "4", "movieTitle": "Inception", …},
{ "id": "5", "movieTitle": "Interstellar", …}
]
我已经尝试使用地图它不起作用这是我的代码
const allNews = this.state.fetchedData.movies.map((data) =>
<ul>
<li key={data.id}>{data.total}</li>
</ul>
);
我收到错误消息:无法读取未定义的属性“地图”
然后我做了一个大的研究,我应该使用 object.key 这是我的代码:
const getData = this.state.fetchedData.map((items, index) => {
return (
<ul key={index}>
{Object.keys(items.movies).map((movie) => {
return (
<li key={movie.id}>{key.movieTitle}</li>
)
})}
</ul>
)
});
我收到错误提示
this.state.fetchedData.map 不是函数
我真的不知道我的问题出在哪里,即使我控制台记录数据我得到了正确的响应
谢谢你们帮助我
【问题讨论】:
-
问题在于您调用地图的方式。根据上面的问题,
this.state.fetchedData.map不是函数,因为this.state.fetchedData是一个对象,map 只能在数组上运行。 -
是的,这就是为什么我尝试使用 Object.keys 将其转换为对象,然后我使用 map 将其转换为数组,但我收到错误消息说我无法隐藏
this.state.fetchedData跨度> -
当你
console.log时,this.state.fetchedData.movies[0]会提供什么? -
@illiteratewriter 我已尝试
console.log(this.state.fetchData.movies[0]);我收到错误无法读取属性'0' of underfined -
试试
this.state.fetchedData.movies[0]
标签: javascript reactjs