简体   繁体   English

为什么 SetState 未在 componentDidMount 上执行

[英]Why SetState not executed on componentDidMount

I want to update a state in ComponentDidMount but the setState function is not being executed我想在 ComponentDidMount 中更新 state 但未执行 setState function

ComponentDidMount() {
    if (this.props.location.search.includes("?token")) {
      const email = getQueryVariable(this.props.location.search, "email");
      const token = getQueryVariable(this.props.location.search, "token");
      if (this.state.showValidationModal === false) {
        console.log("Before",this.state.showValidationModal);
        this.setState({
          showValidationModal:true
        })
        console.log("After",this.state.showValidationModal);

      }
    }
  }

when the application gets mounted the result of both showValidationModal log are false当应用程序被挂载时,两个 showValidationModal 日志的结果都是false

setState is an async operation, it doesn't update the state immediately, But the setState callback, has the last instance value from the state, So. setState是一个异步操作,它不会立即更新 state,但是setState回调具有来自 state 的最后一个实例值,所以。

ComponentDidMount() {
if (this.props.location.search.includes("?token")) {
  const email = getQueryVariable(this.props.location.search, "email");
  const token = getQueryVariable(this.props.location.search, "token");
  if (this.state.showValidationModal === false) {
    console.log("Before",this.state.showValidationModal);
    this.setState({
      showValidationModal:true
    })
    // here you get the latest value of showValidationModal state
    this.setState(prevState => console.log(prevState.showValidationModal))

    // here you get the old value.
    console.log("After",this.state.showValidationModal);

  }
}
}

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

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