axios 同时更新来自单独API调用的2个状态项

bqjvbblv  于 2023-10-18  发布在  iOS
关注(0)|答案(1)|浏览(103)

如何从两个单独的API调用更新一个状态中的两个值(adjustedNetWorth和adjustedLiquidAssets)。我遇到的问题是CombinedNWLADetails状态被覆盖,因为状态更新没有按顺序运行。

const getAdjustedNetWorth = (nwla: ICombinedNWLA) => {
    onCommonGet({
      url: nwlaUrl.calculateAdjustedNetWorth(
        nwla.combinedNetWorth,
        nwla.lessEquity,
        nwla.uncalledCapitalCommitments,
        nwla.calculationOptionId
      ),
      successCallback: (data: number) => {
        console.log('Adjusted Net Worth: ' + data);
        setCombinedNWLADetails({
          ...nwla,
          adjustedNetWorth: data
      })
      },
      recordType: 'Adjusted Net Worth'
    })
  };

  const getAdjustedLiquidAssets = (nwla: ICombinedNWLA) => {
    onCommonGet({
      url: nwlaUrl.calculateAdjustedLiquidAssets(
        nwla.combinedLiquidAssets,
        nwla.lessEquity,
        nwla.uncalledCapitalCommitments,
        nwla.calculationOptionId
      ),
      successCallback: (data: number) => {
        console.log('Adjusted Liquid Assets: ' + data);
        setCombinedNWLADetails({
          ...nwla,
          adjustedLiquidAssets: data
      })
      },
      recordType: 'Adjusted Liquid Assets'
    })
  };
x759pob2

x759pob21#

当你想同时进行多个状态更改时,你应该使用更新函数。React会将更新排队,每个更新都会被调用,并由它的前任产生状态。
范例:

setCombinedNWLADetails(prevNwla => ({
  ...prevNwla,
  adjustedNetWorth: data
}))

setCombinedNWLADetails(prevNwla => ({
  ...prevNwla,
  adjustedLiquidAssets: data
}))

相关问题