【问题标题】:cannot access an array of objects returned from api call in react在反应中无法访问从 api 调用返回的对象数组
【发布时间】:2018-04-16 21:56:39
【问题描述】:

我有一个 API 调用,它在 map 函数中被多次调用以从 mongodb 检索嵌套数据。

结果被推送到一个数组中。 该数组用作子组件的道具数据。

我可以console.log() 结果数组。但我无法在反应中访问它,也无法遍历它。

有谁知道如何解决这个问题。它应该工作。我看不出有什么理由不这样做。越来越郁闷了

fetchMemory(props) {
  const tempMemories = [];
  if (props.journey) {
    props.journey.memories.map((mem) = > {
      superagent
        .get(`/memories/$ {
          mem
        }`)
        .end(function (err, res) {
          let tp = res.body
          tempMemories.push(tp)
        });
    })
    this.setState({
      memories: tempMemories
    })
  }
}

我无法访问在 setstate 中返回的内存数组。如果您在控制台中检查它们,它们确实会显示/它只是在子组件中返回一个错误(作为道具)。

“TypeError: 无法读取未定义的属性‘内存’”

提前致谢。

【问题讨论】:

    标签: arrays reactjs axios superagent


    【解决方案1】:

    通过 axios 获取数据是异步的,所以基本上 tempMemories 在您调用 setState() 时为空,因为网络调用尚未完成。

    你应该像这样使用Promise.all

    const promiseList = props.journey.memories.map( mem => {
      return superagent
         .get(`/memories/${mem}`)
         .then( res => res.body );
    });
    
    Promise.all( promiseList )
      .then( results => {
        this.setState({
          memories: results
        });
      })
      .catch( err => {
        ...
      });
    

    所以基本上你为每个元素创建一个承诺,然后等待所有元素都得到解决以执行setState() 调用。

    【讨论】:

    • 非常感谢您的回答!真的很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2021-03-30
    • 2011-03-29
    • 1970-01-01
    • 2021-01-25
    • 2019-06-14
    • 2017-04-06
    • 1970-01-01
    • 2020-10-02
    相关资源
    最近更新 更多