【发布时间】:2019-03-18 15:10:45
【问题描述】:
constructor(props){
super(props);
this.state = {
posts: [],
}
}
componentWillMount() {
fetch("https://newsapi.org/v2/top-headlines?country=us&apiKey=${API_KEY}")
.then(res => res.json())
.then(data => this.setState({posts:data}));
}
render() {
return (
<div>
<ul>
{ this.state.posts.map(post => <li key={post.id}>{post.title}</li>) }
</ul>
</div>
)
}
我正在尝试映射此新闻对象的标题,但每当我尝试这样做时,我都会收到此错误:TypeError: this.state.posts.map is not a function。 这是来自数据的对象图片:https://i.imgur.com/ctvXXWA.png
【问题讨论】:
-
做
console.log(data)看看里面有什么。我相信根据你的错误,data不是一个数组。 -
这是数据图片:i.imgur.com/ctvXXWA.png
-
@arup 根据问题标题“我如何映射对象”,
data也不是数组。 -
图中数据是一个名为articles的数组,而不是一个名为posts的对象??
-
帖子只是一个包含数据的状态。
标签: javascript reactjs