【问题标题】:Why my array is empty? React reading json api为什么我的数组是空的? React 读取 json api
【发布时间】:2018-07-29 19:22:10
【问题描述】:

这是来自我的 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"
    }
]

它有两个由括号分隔的元素 {} 这就是我尝试在我的反应组件中使用 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) = 未定义

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

中的第 27 行中断了

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

这是错误信息:

未处理的拒绝 (TypeError):无法读取属性“forEach”的 未定义

还有来自控制台的错误:

Uncaught (in promise) TypeError: Cannot read property 'forEach' of 未定义

【问题讨论】:

    标签: javascript reactjs fetch


    【解决方案1】:

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

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

    这就是您将收到 "Cannot read property 'forEach' of undefined" 错误的原因 - 您尝试在未定义的 .results 字段上调用 ​​.forEach(..)postPrvSrv 数组上。

    要解决此问题,请尝试调整您的代码,如下面的 cmets 所示:

    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])})
      })
    
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-10
      • 2017-11-01
      • 2019-03-18
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-29
      相关资源
      最近更新 更多