【问题标题】:Calling React js Fetch Calls In a Sequence在序列中调用 React js Fetch 调用
【发布时间】:2020-11-28 12:52:35
【问题描述】:

有人,请帮我一个接一个地调用这些 fetch Api,因为我正在使用存储在后端的数据来处理我的下一个请求。我希望以这种方式依次调用它们一个完整然后下一个请求。

 Promise.all([
   fetch(`http://localhost:5000/zoomapi`, 
    requestOptions),

    fetch('http://localhost:5000/getId')
    .then((res) => res.json())
    .then((result) => {
        this.setState({ zoomid: result });      
    }),

   fetch(`http://localhost:5000/users/zoom?name=${this.state.zoomid}`)
   .then((res) => res.json())
   .then((result) => {
       this.setState({ zoomdata: result });
      })  
  ])
   .catch((error) => {
       this.setState({ error });
   });


  })

【问题讨论】:

    标签: javascript node.js reactjs api fetch


    【解决方案1】:

    .setState不是同步操作,所以不能用const id = this.state.zoomid,可以用result代替。此外,你的承诺应该是链式的,而不是嵌套的。示例:

    fetch('http://localhost:5000/getId')
        .then((res) => res.json())
        .then((result) => {
            this.setState({ zoomid: result });
            return fetch(`http://localhost:5000/users/zoom?name=${result}`);
        })
        .then((res) => res.json())
        .then((result) => {
            this.setState({ zoomdata: result });
        })
        .catch((error) => {
            this.setState({ error });
        });
    

    【讨论】:

    • 对不起,如果我不清楚我的问题。但是我在上述两次提取之前调用了一次提取,其中我更新了节点后端中的变量,当我使用“/getId”时,我想要更新的变量 id,我仍然得到旧的临时变量。所以请帮忙。感谢您的承诺建议,我已经进行了更改而不是嵌套。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多