代码之家  ›  专栏  ›  技术社区  ›  ValRob

为什么我的数组是空的?React读取JSON API

  •  2
  • ValRob  · 技术社区  · 7 年前

    这是我在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"
        }
    ]
    

    它有两个元素,用括号分隔 这就是我想用的方法 在我的反应组件中。

    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); =没什么,因为它在27号线坏了。在 前额

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

    这是错误消息:

    未处理的拒绝(类型错误):无法读取的属性“foreach” 未定义

    控制台的错误:

    未捕获(承诺中)类型错误:无法读取的属性“foreach” 未定义

    1 回复  |  直到 7 年前
        1
  •  2
  •   Dacre Denny    7 年前

    postPrvSrv

    .results undefined

    .forEach(..)

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