javascript - 循环 Fetch_API 似乎对我不起作用

标签 javascript html reactjs

我已经从 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;

![The error I am getting in the console: ] 1

最佳答案

看来从 API 返回的数据是一个带有 posts 键的对象。
因此,要么使用 data.posts 设置状态,要么循环 posts.posts

我认为第一个选项似乎更合理。

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

关于javascript - 循环 Fetch_API 似乎对我不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55881878/

相关文章:

javascript - ajax 在 Laravel 中无法工作,显示找不到页面

javascript - onDrop 事件转发到 url 但仅在 FireFox 中

javascript - 当我在特定表单元素上单击 "enter"时拒绝提交

javascript - jQuery 迭代 .each() 并根据第一个 .each() 给出迭代 id

javascript - 如何更改动态生成的选项表单元素的innerHTML

html - 对表行中的所有元素应用缩放变换

javascript - CSS-3 转换错误,菜单出现卡住

javascript - 滚动开始时调用方法

javascript - React/javascript 如何将 json 形式的表数据导出到可下载的 Excel 中

javascript - 无法从 'C:\Users\syrine\management\node_modules\stylis-plugin-rtl\src\stylis-rtl.ts' 解析源映射