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 不是函数。 这是数据中对象的图片:/image/3fnlg.png
最佳答案
使用 Object.keys() 返回对象的数组
{Object.keys(posts).map((item, i) => (
<li key={i}>{posts[item].title}</li>
))}
关于javascript - 如何映射对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52795576/