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

dced5bon  于 5个月前  发布在  iOS
关注(0)|答案(3)|浏览(83)

我使用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的函数。
我的问题是-这是实现我的目标的最佳解决方案吗?或者我应该在两种情况下重复这段代码?

bejyjqdl

bejyjqdl1#

您应该使用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的promise,那么你应该用.then替换.finally,因为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 })
});

flseospp

flseospp2#

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

0ve6wy6x

0ve6wy6x3#

使用当前方法会遇到的一个问题是,任何可能的错误都将阻止最后一个.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 })

字符串

相关问题