setState immediately update! Pass function to setState

298 阅读1分钟

Typically you pass {} to setState:

class User {
 state={
     score:0
 }
  ... 
  increaseScore () {
    this.setState({
        score : this.state.score + 1
    });
  }
  ...
}

Now you can pass Func() to setSate and return {}:

 this.setState(
       function (state, props) {  //pass this current state and props to func.
 return {  //return the same object {} as above...
         score: state.score - 1
     }
}
    );
    

**Now what really surprises many people is that you can define the setState func outside of the compnt!!! **

this.setState(setScore);

Move the function out of the component.

const setScore=(passedState, passedProps)=>{ return { score: passedState+2; } }

COOL!@@@@@@@@@@@@@@@

Why?????

Because:

setSate will be mergered and batched in queues if you use traditional setState, if you use functional setState...it will guarantee to update and will NOT merged.

Now what we can do is to guarantee react to setState everytime we call it, now modifying below code.

this.setState(
      updater,
      () => {
        console.log(this.state);
      }
      )

const updater = (passedState, passedProps) => {
  //  console.log(passedState,passedProps)
  return {
    firstName: {
      ...passedState["firstName"],
      ...{ value: "updated", valid: true }
    }
  };
};

Or you can even use chains to setState!!


handleChange = field => event => {
    var v = event.target.value;
    // this.state[field] = value;
    this.setState(
      (currentState, currentProps) => {
        return {
          [field]: { ...currentState[field], ...{ value: v } }
        };
      },  //first time use updater...
      () => { //callBack
        //console.log(this.state);
        var valid = vaidate(field, this.state[field].value);
        this.setState( //second time use direct obj
          {
            [field]: Object.assign({}, this.state[field], { valid: valid })
          },
          () => {
            console.log(this.state);  //finally check console.log to see if state full update!!!!
          }
        );
      }
    );
  }; //use brqcket to enclose name of obj...
  // };