如何在两种情况下有效地调用setState - 成功和错误?

问题描述 投票:0回答:3

我正在使用react,我有一个异步操作,使用axios从API接收一些数据。我还有一个标志(状态变量tableLoaded),它描述了是否获取数据。

    this.props.fetchDataAction(requestParams).then(
      () => {
        this.setState({
          data: this.props.reports.data
        });
      }
    ).then(() => {
      this.setState({ tableLoaded: true })
    });

我希望我的标志tableLoaded在两种情况下都设置为true - 在API调用成功后失败,所以我只在我的Promise上添加了另一个then(),它触发了将此标志设置为true的函数。

我的问题是 - 这是实现我的目标的最佳解决方案吗?或者我应该在两种情况下重复此代码?

javascript reactjs api call axios
3个回答
1
投票

您应该使用Promise.finally语法。

this.props.fetchDataAction(requestParams)
.then(() => {
    // Do your thing on success
    this.setState({
        data: this.props.reports.data
    });
})
.catch((error) => {
    // Do something if failed
})
.finally(() => {
    // Do this in all cases..
    this.setState({ tableLoaded: true })
});

编辑:如果fetchDataAction的回报是Axios承诺,那么你应该用.finally替换.then,因为Axios不提供finally方法。然后我会说你的原始建议是正确的。你可以评论第二个.then所以你知道为什么。

this.props.fetchDataAction(requestParams)
.then(() => {
    // Do your thing on success
    this.setState({
        data: this.props.reports.data
    });
})
.catch((error) => {
    // Do something if failed
})
.then(() => { // Triggered in all cases by axios
    // Do this in all cases..
    this.setState({ tableLoaded: true })
});

0
投票

您可以使用all()来捕捉成功和失败


0
投票

使用当前方法遇到的一个问题是,任何可能的错误都会阻止最后的.then运行,如果出现问题,tableLoaded可能会保留falseSee this pen for an example of this issue.

另一个答案指出,Promise.finally是一个很好的方法来解决这个问题,但我个人的偏好是使用async/await

try {
  await this.props.fetchDataAction(requestParams)
  this.setState({
    data: this.props.reports.data
  })
} catch (error) {
  // handle error
}
this.setState({ tableLoaded: true })
© www.soinside.com 2019 - 2024. All rights reserved.