Why does calling react setState method not mutate the state immediately?

2022-08-29 23:29:37

I'm reading Forms section of documentation and just tried this code to demonstrate usage (JSBIN).onChange

var React= require('react');

var ControlledForm= React.createClass({
    getInitialState: function() {
        return {
            value: "initial value"
        };
    },

    handleChange: function(event) {
        console.log(this.state.value);
        this.setState({value: event.target.value});
        console.log(this.state.value);

    },

    render: function() {
        return (
            <input type="text" value={this.state.value} onChange={this.handleChange}/>
        );
    }
});

React.render(
    <ControlledForm/>,
  document.getElementById('mount')
);

When I update the value in the browser, the second inside the callback prints the same as the first , Why I can't see the result of in the scope of callback?<input/>console.loghandleChangevalueconsole.logthis.setState({value: event.target.value})handleChange


答案 1

From React's documentation:

setState() does not immediately mutate but creates a pending state transition. Accessing after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to and calls may be batched for performance gains.this.statethis.statesetState

If you want a function to be executed after the state change occurs, pass it in as a callback.

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

答案 2

As mentioned in the React documentation, there is no guarantee of being fired synchronously, so your may return the state prior to it updating.setStateconsole.log

Michael Parker mentions passing a callback within the . Another way to handle the logic after state change is via the lifecycle method, which is the method recommended in React docs.setStatecomponentDidUpdate

Generally we recommend using componentDidUpdate() for such logic instead.

This is particularly useful when there may be successive s fired, and you would like to fire the same function after every state change. Rather than adding a callback to each , you could place the function inside of the , with specific logic inside if necessary.setStatesetStatecomponentDidUpdate

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