【问题标题】:React.js, how to use map and async functions with setState callback?React.js,如何使用带有 setState 回调的 map 和 async 函数?
【发布时间】:2020-10-08 00:57:44
【问题描述】:

在我的 React 应用程序中,我需要为我的地图结果中的每条记录连续调用 2 个不同的函数。

通过调用函数 getOrderLine() 和关于记录的数量,我想为地图结果中的每条记录依次调用函数 getItemInfo() 和 createOrderLine()。

下面代码的预期行为是这样的(我们假设我们有 2 条记录):

1-调用 getItemInfo()
2-调用 createOrderLine()
3-调用 getItemInfo()
4-调用createOrderLine()

但我有这个:

1-调用 getItemInfo()
2-调用 getItemInfo()
3-调用 createOrderLine()
4-调用 createOrderLine()

我尝试使用异步和承诺,但我未能解决问题。

以下是代码源,感谢您的帮助。

getOrderLine = () => {

    axios
      .post(
        this.hostname +`getPoLine.p?id=` +  this.id 
      )
      .then(response => {

        response.data.ProDataSet.tt_order_line.map( item=>{
            this.setState({
                quantity: item.quantity,
                price: item.price
            },()=>{this.getItemInfo()})
        })        
    })
  }

getItemInfo = () => {   

    /* some code */
            this.setState({

                order_code: "value 1",
                alloc_qty: 20,
            },()=>{this.createOrderLine()})
}

【问题讨论】:

  • 为什么需要setState?你只是想按顺序调用api吗?
  • 你在循环中调用 setState 。真的需要吗?
  • 是的,因为 getItemInfo() 需要 getOrderLine 函数提供的数量和价格的新值。 createOrderLine() 还需要 order_code 和 alloc_qty 的新值来调用 api。

标签: reactjs promise async-await map-function asynccallback


【解决方案1】:

要按顺序运行所有代码,您需要编写承诺链:

var getOrderLine = () => {
  axios
    .post(this.hostname + 'getPoLine.p?id=' + this.id)
    .then(response => {
      let i = 0
      next()

      function next (err) {
        if (err) {
          // an error occurred
          return
        }

        if (i >= response.data.ProDataSet.tt_order_line.length) {
          // processed all the lines
          return
        }

        const item = response.data.ProDataSet.tt_order_line[i]
        i++

        this.setState({
          quantity: item.quantity,
          price: item.price
        }, () => {
          this.getItemInfo()
            .then(() => {
              return this.createOrderLine() // assume it returns a promise
            })
            .then(next)
            .catch(next)
        })
      }
    })
}

var getItemInfo = () => {
  return new Promise(resolve => {
    this.setState({
      order_code: 'value 1',
      alloc_qty: 20
    }, resolve)
  })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 2019-09-21
    • 2018-09-16
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    相关资源
    最近更新 更多