我有一个 React 页面,基于 Axios
调用失败,我将错误 state
设置为 true,默认情况下为 false。当其为 true
时,我会显示错误。我尝试使用 componentDidMount
来实现,如下所示:
componentDidMount() {
const showError = this.state.saveError;
if(showError) {
setTimeout(() => {
this.setState({
saveError: false
})
}, 3000)
}
}
但它似乎不起作用,因为一旦设置为 true,总是会显示错误。我如何解决它?还有其他建议吗?
谢谢
最佳答案
更新componentDidUpdate
中的状态,因为只要组件中有更新,componentDidUpdate
生命周期方法就会执行。
示例代码:
componentDidUpdate() {
const showError = this.state.saveError;
if (showError) {
setTimeout(() => {
this.setState(prevState => {
return {
...prevState
saveError: false
}
})
}, 3000)
}
}
关于javascript - 如何更改 componentDidMount 中的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59642567/