我正在使用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的函数。
我的问题是 - 这是实现我的目标的最佳解决方案吗?或者我应该在两种情况下重复此代码?
您应该使用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 })
});
您可以使用all()
来捕捉成功和失败
使用当前方法遇到的一个问题是,任何可能的错误都会阻止最后的.then
运行,如果出现问题,tableLoaded
可能会保留false
。 See 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 })