Why calling setState method doesn't mutate the state immediately?

前端 未结 3 789
面向向阳花
面向向阳花 2020-11-21 15:22

Ok, i\'ll try and make this quick because it SHOULD be an easy fix...

I\'ve read a bunch of similar questions, and the answer seems to be quite obvious. Nothing I wo

3条回答
  •  甜味超标
    2020-11-21 16:07

    Since setState is a async function. That means after calling setState state variable does not immediately change. So if you want to perform other actions immediately after changing the state you should use callback method of setstate inside your setState update function.

    handleOnChange = (event) => { 
         let inputState = event.target.checked;
          if(event.target.className == "barClubLounge") {
             this.setState({ barClubLounge: inputState}, () => {  //here
                 console.log(this.state.barClubLounge);
                 //here you can call other functions which use this state 
                 variable //
             });        
          }
       }
    

提交回复
热议问题