【问题标题】:How to send fetch requests after getting a response from the previous request in React?从 React 中的上一个请求获得响应后,如何发送 fetch 请求?
【发布时间】:2020-05-15 12:08:43
【问题描述】:

我有一个变量details,需要通过向“/abc”发送获取请求来填充它。之后我需要访问details 变量中的值以将其他请求发送到'/def'。

我无法理解我该怎么做。

我正在使用两个独立的函数。首先是updateDetails(),它更新了details 状态,我称之为componentDidMount()。第二种方法是sendOtherRequests(),我需要在details 具有所有值之后调用它。

问题是我在componentDidMount() 中添加了这两个函数,但由于它们是异步调用,因此在details 完全填充之前进行了调用。

我的代码如下所示:

updateDetails = () => {
    ...get('abc')
      .then(data => {
        this.setState({
          details: data
        })
      })
  }

sendOtherRequests = () => {
   
   for(let i in details) {
    ...get('def/' + i)
      .then(res => {
        // save data
      })
      .catch(err => {
        console.log('error caught ' + JSON.stringify(err))
        return false
      })
   }
  }

我将不胜感激。我对 React 有点陌生。

【问题讨论】:

    标签: javascript reactjs asynchronous get


    【解决方案1】:

    sendOtherRequests 中发送请求所需的数据将在get('abc')then 块 中提供。尝试在那里调用sendOtherRequests

    updateDetails = () => {
        ...get('abc')
          .then(data => {
            ...your code
            sendOtherRequests()
          })
      }
    

    【讨论】:

    • 我对 React 和这个获取请求有点陌生,所以如果我错了,请纠正我。获取请求是异步的,所以即使我在 then() 子句中调用,details 变量真的会被填满吗?
    • 当您执行任何获取请求时,它会返回 promise。Promise 可以处于待处理、已完成、已拒绝等任何状态。因此,如果 promise 处于待处理状态并在一段时间后解决,您将获得数据。然后 block 是你的数据在 promise 得到解决后可用的地方。
    • 嘿@Panda 你找到解决方案了吗?
    【解决方案2】:

    试试这个希望这对你有用。

    updateDetails = () => {
        ...get('abc')
          .then(data => {
            this.setState({
              details: data
            },()=>{
                 someOtherRequests()
                  })
          })
      }
    

    【讨论】:

      【解决方案3】:

      你可以给你的 setState 一个回调,即当状态更新时,你可以调用你的其他请求:

      updateDetails = () => {
          ...get('abc')
            .then(data => {
              this.setState({
                details: data
              }, sendOtherRequests)
            })
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-29
        • 2019-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-19
        • 1970-01-01
        相关资源
        最近更新 更多