javascript - 为什么我的数组是空的? React 读取 json api

标签 javascript reactjs fetch

这是来 self 的 Drupal 站点的 json:

[
    {
        title: "I believe every human has a finite number of heartbeats. I don't intend to waste any of mine.",
        uid: "gestor"
    },
    {
        title: "Man must explore, and this is exploration at its greatest",
        uid: "gestor"
    }
]

它有两个用方括号分隔的元素 {} 这就是我尝试在我的 React 组件中使用 Fetch 的方式。

componentWillMount(){
    // Con fetch me conecto al site de Drupal
    fetch('http://rest.dd:8080/all-of-us')
    .then(response => response.json())
    .then(postPrvSrv => {
      // A cada post lo coloco en un array
      console.log(postPrvSrv.results)
      postPrvSrv.results.forEach(post => {
        let data = {
          title:post.title,
          author:post.uid
        }
        console.log(data);
        // Actualizamos el state para poder renderizar
        this.setState({postPrvSrv:this.state.postPrvSrv.concat([data])})
      })
    })
  }

这是我的控制台日志结果:

console.log(postPrvSrv.results) = undefined

console.log(data); = Nothing,因为它在 forEach

的第 27.. 行中断了

console.log(this.state.postPrvSrv.length) = 0。

这是错误信息:

Unhandled Rejection (TypeError): Cannot read property 'forEach' of undefined

来自控制台的错误:

Uncaught (in promise) TypeError: Cannot read property 'forEach' of undefined

最佳答案

如果您直接从 Durpal 端点返回一个数组,那么 postPrvSrv 变量(在您的获取响应处理程序中)将是一个普通数组。

假设 postPrvSrv 是一个数组,那么 postPrvSrv 上的 .results 字段将是 undefined

这就是您将收到 “无法读取未定义的属性 'forEach'” 错误的原因 - 您正在尝试调用 .forEach(..).results 字段上,它在 postPrvSrv 数组中未定义。

要解决此问题,请尝试按照以下评论所示调整您的代码:

fetch('http://rest.dd:8080/all-of-us')
.then(postPrvSrv => {

  console.log(postPrvSrv) // Fix this line to see log of data in console

  postPrvSrv.forEach(post => {  // Fix this line
    let data = {
      title:post.title,
      author:post.uid
    }
    console.log(data);

    this.setState({postPrvSrv:this.state.postPrvSrv.concat([data])})
  })

})

关于javascript - 为什么我的数组是空的? React 读取 json api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51579704/

相关文章:

javascript - 图像不会隐藏在滚动 jQuery 上

reactjs - 我可以更改图表中 YAxis 中特定值的样式吗?

javascript - 如何在 JavaScript 中传递 POST 请求 URL 内的变量?

Mysql从相似但不相关的表中获取数据

javascript - 音频传输android和node-webkit

Javascript 在特定位置之后删除数组中的项目

javascript - 将 React 小部件嵌入到另一个网站中

javascript - 从 React.js 中的 json 文件中获取数据

javascript - 将字符串文字内的函数传递给其他组件

reactjs - useState 数组 bool 切换 - React Native