首页 > 解决方案 > 循环通过 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

标签: javascripthtmlreactjs

解决方案


从 API 返回的数据似乎是一个带有posts键的对象。
所以要么设置状态,data.posts要么循环posts.posts

在我看来,第一种选择似乎更合理。

this.setState({
      posts: data.posts,
      isLoading: false,
    })

推荐阅读