【问题标题】:How to set state in React JS for multiple API calls?如何在 React JS 中为多个 API 调用设置状态?
【发布时间】:2021-02-02 03:20:49
【问题描述】:

此 url http://127.0.0.1:5051/load/ 将返回值列表(例如:list_val =['a','b','c','d'])。对于列表中的每个值,都会调用一个 api(http://127.0.0.1:5051/sample/"+**list_val[i]**+"/version),并且所有 api 的响应都应该分配给状态变量。我怎样才能做到这一点?我应该创建一个列表并将每个api的响应推送到列表中然后设置状态吗?

componentDidMount(){
      fetch("http://127.0.0.1:5051/load/") 
      .then(response =>{
          return response.json();
      }) 
      .then(data => {
          let fromapi = data
          var version_len = fromapi.length;
          for (var i=0; i<version_len; i++){
            //console.log(fromapi[i])
            fetch("http://127.0.0.1:5051/sample/"+fromapi[i]+"/version") 
                .then(response =>{
                      return response.json();
             }) 
             .then(data=>{
               let version_api = data
               console.log(version_api)
                this.setState({
                  version : version_api
               })
             })
          }
       })
       .catch(error=>{
          console.log(error);
       })
   }

【问题讨论】:

  • 列表中的每个项目是否有不同的版本号?状态变量的结构是什么?
  • 是的!每个项目的版本号都不同。 this.state = { 版本:[] }

标签: reactjs


【解决方案1】:
async componentDidMount=()=>{
  fetch("http://127.0.0.1:5051/load/") 
  .then(response =>{
      return response.json();
  }) 
  .then(data => {
      let fromapi = data
      var version_len = fromapi.length;
      for (var i=0; i<version_len; i++){
        //console.log(fromapi[i])
        fetch("http://127.0.0.1:5051/sample/"+fromapi[i]+"/version") 
            .then(response =>{
                  return response.json();
         }) 
         .then(data=>{
           let version_api = data
           console.log(version_api)
         await  this.setState({ 

              version : version_api
           })
         })
      }
   })
   .catch(error=>{
      console.log(error);
   })
}

Why does Async Await work with React setState?

【讨论】:

  • 最好解释一下您的问题/问题以及您尝试过的事情。
【解决方案2】:

你应该像这样创建状态值。

this.state = {
 versions: []
}

那么你应该像这样更改代码。

.then(data=>{

   const versions = { this.state };

   versions.push(data);

   this.setState({ versions });

})

【讨论】:

    【解决方案3】:

    Promise.allSettled() 只会在所有请求都满足(成功/失败)时返回。

    如果所有请求都依赖,您可以使用Promise.all(),因为它会在任何输入承诺拒绝或非承诺引发错误时立即拒绝,并会在第一个拒绝消息/错误中拒绝。

    参考所提供的代码,考虑遵循 sn-p。

    const promiseArray = [];
    
    for (var i=0; i<version_len; i++){
       promiseArray.push(
            fetch("http://127.0.0.1:5051/sample/"+fromapi[i]+"/version")
               .then(res => res.json() /*convert to JSON here */
            )
       );
    })
    
    Promise.allSettled(promiseArray).then(versions => {
        // Here, you will get array of all API calls in same sequence of initiation.
    
       // Associate each version number with its item
       const itemsWithVesion = versions.map((version, i) => (
          {
            item: fromApi[i],
            version: version 
          })
       
       // Finally, update the state
       this.setState({ itemsWithVersion });
    });
    

    【讨论】:

    猜你喜欢
    • 2022-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 2017-06-26
    • 2021-03-26
    • 2021-06-06
    • 2017-06-16
    相关资源
    最近更新 更多