I'm reading Forms section of reactjs documentation and just tried this code to demonstrate onChange
usage (JSBIN).
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 <input/>
value in the browser, the second console.log
inside the handleChange
callback prints the same value
as the first console.log
, Why I can't see the result of this.setState({value: event.target.value})
in the scope of handleChange
callback?
You could try using ES7 async/await. For instance using your example:
From React's documentation:
If you want a function to be executed after the state change occurs, pass it in as a callback.
async-await
syntax works perfectly for something like the following...As mentioned in the React documentation, there is no guarantee of
setState
being fired synchronously, so yourconsole.log
may return the state prior to it updating.Michael Parker mentions passing a callback within the
setState
. Another way to handle the logic after state change is via thecomponentDidUpdate
lifecycle method, which is the method recommended in React docs.This is particularly useful when there may be successive
setState
s fired, and you would like to fire the same function after every state change. Rather than adding a callback to eachsetState
, you could place the function inside of thecomponentDidUpdate
, with specific logic inside if necessary.Watch out the react lifecycle methods!
I worked for several hours to find out that
getDerivedStateFromProps
will be called after everysetState()
.