javascript - 有没有办法为 foreach 的每次迭代设置状态

标签 javascript reactjs foreach

我正在 React 应用程序中使用 API,我正在尝试让 API 调用作为一个 promise 返回。

我正在使用效果很好的 Promise.all() 方法。

我一直在尝试将两个 API 调用的结果设置为具有它们自己的名称的状态。 promise 代码工作正常,我正在尝试对两组数据执行 forEach() 或 map() 并将它们保存到 state 用自己的名字。

我确信有一个简单的解决方案,但我为此挠头太久了!

我已经尝试在所有文档中搜索 .map 和 .forEach,但没有成功!

fetchData(){
this.setState({loading: true})
const urls = ['https://api.spacexdata.com/v3/launches/past', 'https://api.spacexdata.com/v3/launches']

let requests = urls.map(url => fetch(url));
Promise.all(requests)
  .then(responses => {
    return responses
  })
  .then(responses => Promise.all(responses.map(r => r.json())))
  .then(launches => launches.forEach(obj => {
    // I need to set both values to state here
  }))
  .then(() => this.setState({loading: false}))
  }

API 调用返回两个不同的数组。我需要使用自己的名称将两个数组分别设置为 State。这可能吗?

最佳答案

如果我正确理解您的问题,更好的方法可能是完全避免迭代(即使用 forEach() 等)。相反,考虑一种基于“destructuring syntax”的方法,看到您在数组中有已知/固定数量的项目,这些项目是根据先前的 promise 解决的。

您可以通过以下方式使用此语法:

/* 
   The destructing syntax here assigns the first and second element of
   the input array to local variables 'responseFromFirstRequest'
   and 'responseFromSecondRequest' 
*/
.then(([responseFromFirstRequest, responseFromSecondRequest]) => {

      // Set different parts of state based on individual responses
      // Not suggesting you do this via two calls to setState() but
      // am doing so to explicitly illustrate the solution

      this.setState({ stateForFirstRequest : responseFromFirstRequest });
      this.setState({ stateForSecondRequest : responseFromSecondRequest });

      return responses
    })

因此,集成到您现有的逻辑中,它看起来像这样:

fetchData() {
  this.setState({
    loading: true
  })
  
  const urls = ['https://api.spacexdata.com/v3/launches/past', 'https://api.spacexdata.com/v3/launches']

  const requests = urls.map(url => fetch(url));
  
  Promise.all(requests)
    .then(responses => Promise.all(responses.map(r => r.json())))
    .then(([responseFromFirstRequest, responseFromSecondRequest]) => {
    
      this.setState({ stateForFirstRequest : responseFromFirstRequest });
      this.setState({ stateForSecondRequest : responseFromSecondRequest });
    
      return responses
    })
    .then(() => this.setState({
      loading: false
    }))
}

关于javascript - 有没有办法为 foreach 的每次迭代设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54100976/

相关文章:

javascript - 在 html 和 javascript 中使用 div 切换内容

javascript - 所有字谜 - 递归

Javascript原型(prototype)扩展方法

reactjs - 如何使用 MemoryRouter 来测试 useParams 调用

javascript - DOMException 权限被拒绝 - 定期后台同步

javascript - 如何从数据表中获取最后插入的行

javascript - 如何在另一个组件的渲染方法中渲染存储在数组中的 React 组件

jquery - 请解释下面的代码

javascript - 将多个值添加到数组中时出现问题

php - 每个 foreach javascript/php 之间的延迟