简体   繁体   English

如何更改 componentDidMount 中的状态?

[英]How to change state in componentDidMount?

I have a react page and based upon an Axios call failure, I set error state to true which is false by default.我有一个反应页面,基于Axios调用失败,我将错误state设置为 true,默认情况下为 false。 When its true , I show an error.当它为true ,我会显示错误。 I tried to use componentDidMount for that as below:我尝试使用componentDidMount如下:

componentDidMount() {
  const showError = this.state.saveError;
  if(showError) {
    setTimeout(() => {
      this.setState({
        saveError: false
      })
    }, 3000)
  }
}

But it doesn't seems to work as the error is always displayed once set to true.但它似乎不起作用,因为一旦设置为 true,就会始终显示错误。 How do I fix it?我如何解决它? Any other suggestion?还有什么建议吗?

Thanks谢谢

Update the state in componentDidUpdate as the componentDidUpdate life cycle method will execute whenever there is an update in component.更新的状态componentDidUpdate作为componentDidUpdate生命周期方法,每当有在部件的更新将被执行。

Sample Code:示例代码:

 componentDidUpdate() {
    const showError = this.state.saveError;
    if (showError) {
        setTimeout(() => {
            this.setState(prevState => {
                return {
                    ...prevState 
                    saveError: false
                }
            })
        }, 3000)
    }
}

Please show your initialState.请显示您的初始状态。 Please explain what are you trying to do here, because I don't see any Axios request.请解释您要在这里做什么,因为我没有看到任何 Axios 请求。

Assign value of state to variable doesn't make any sense: const showError = this.state.saveError;将状态值赋给变量没有任何意义: const showError = this.state.saveError;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM