javascript - 循环通过 Fetch_API 似乎对我不起作用
问题描述
我已经从 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,
})
推荐阅读
- sqlite - 无法找出我的“with”中的语法错误
- c++ - 函数模板参数推导和继承
- php - 如果在 CodeIgniter 中没有选择要更新的图像,如何从数据库中设置图像的路径
- html - 使用 Gmail 的 html 电子邮件中的网络字体
- android - 使用动态 JSON 数组名称改造响应
- c# - 无效的表达式术语“字符串”C#
- php - 将活动类添加到特定的菜单 wordpress
- cookies - Chrome-Dev-Tool :- 亚马逊中的 csm-hit cookie
- python - 为什么我的代码没有遵循 if/else 语句而是跳转到不同的地方?
- keras - 使用 Keras 模型的前 4 名预测