简体   繁体   中英

State in React not changing with setState method

I am trying to update my state with setState method in one of my functions but state doesn't somehow change. I am also using if statement in that function to tell the setState when to actually change state. I get back correct message in console.log when if statement is true but my state still doesn't change. What could cause the error?

My function and state:

constructor(props) {
    super(props);
    this.state = {
        isregistered: false
    }
}

handleValidate = (validate) => {
    const state1 = this.state
    console.log('state1', state1)
    const validate1 = validate
    console.log('l]plik validate', validate1)
    if ( validate.length != 0){
        this.setState({
            isregistered: true
        })
        console.log('onregatud', this.state.isregistered)
   }
   else{
        console.log('mitteregatud', this.state.isregistered)
   }
}

It is not an error, setState is asynchronous. If you want to check the state right after a setState you need to pass a callback :

this.setState({myState : newState}, () => console.log(this.state.myState))

The setState() operation is asynchronous and your console.log() will be executed before the setState() mutates the value of isregistered where you set it from false to true and hence you are not able to see the result.

We can solve this issue by two ways:

  1. By passing a callback function to the setState()

     const handleValidate = (validate) => { const state1 = this.state const validate1 = validate if ( validate.length != 0){ this.setState( { isregistered: true }, () => console.log('callback fired', this.state)); } else { console.log('mitteregatud', this.state.isregistered); } }
  2. By using async-await

     async function handleValidate(validate) { const state1 = this.state const validate1 = validate if ( validate.length != 0){ await this.setState({ isregistered: true}) // More code here based on state outside callback console.log('onregatud', this.state.isregistered) } else { console.log('mitteregatud', this.state.isregistered) } }

    Using async-await is cleaner instead of using a callback in setState()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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