how to access this.state after it has been set?

293 阅读1分钟

Method 1: call back...

this.setState(
  {value: event.target.value}, 
   
    ()=> {
    console.log(this.state.value);
}
);

Update: If the state structure is nested obj..use this istead...

  state = {
    email: {
      value: "",
      validation: false
    },
    password: {
      value: "",
      validation: false
    },
    validateForm: false,
    nameSubmit: "offSubmit"
  };

setState immediately with below: stackoverflow.com/questions/5…

handleChange = e => {
    this.setState({
    
      [e.target.name]: Object.assign( {}, this.state[e.target.name], { value: e.target.value } )
        
    },
      () => {
            if (e.target.name === "email") {
              // "this.state.email.value" has an updated value here.
            }

            if (e.target.name === "password") {
              // "this.state.password.value" has an updated value here.
            }
      }
    });

    this.checkForm(e);
  };

Update on this assignment, using spread operator...like so:


[e.target.name]:  (... this.state[e.target.name], ... { value: e.target.value } )

See what redux say!!

Note: in order to pass the data to parent, you can use the below pattern, where the call back is sent by parent, named consumeData

  this.setState({
    data: data
  }, () => this.props.consumeData(this.state.data)); // using `data` would work as well...
}

Method 2: lifecycle ComponentDidUpdate

componentDidUpdate(prevProps, prevState) {
  if (this.state.value > prevState.value) {
    this.foo();  
  }
}

Note: the first arg is prevProps NOT prevState!!1