我已经从 API 获取数据并尝试循环从 URL 收到的 json 数据,但我收到错误,它说“posts.map 不是一个函数”。我已经通过互联网查看但无法收到我正在寻找的答案。感谢您的帮助!
这是我的reactjs代码:
class App extends React.Component {
state = {
isLoading: true,
posts: [],
error: null,
users: []
}
async componentDidMount(){
const URL_API = `https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/posts.json`;
const response = await fetch(URL_API);
const data = await response.json(); //this is asyncronous calls that
return us the json data
this.setState({
posts: data,
isLoading: false,
})
}
render() {
const { posts } = this.state
console.log('posttt', posts);
return (
<React.Fragment>
<h1>React fetch - Blog</h1>
<hr />
<ul id='list'>
{posts.map(post => (
<li
key={post.id}>
<span>{post.title}</span>
<span>{post.content}</span>
</li>
))}
</ul>
</React.Fragment>
);
}
}
export default App;
] 1
最佳答案
看来从 API 返回的数据是一个带有 posts
键的对象。
因此,要么使用 data.posts
设置状态,要么循环 posts.posts
。
我认为第一个选项似乎更合理。
this.setState({
posts: data.posts,
isLoading: false,
})
关于javascript - 循环 Fetch_API 似乎对我不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55881878/