When I use the Chrome console to check the state of my component in the render
method, I get the up-to-date state value.
However, when I display this state in a div
, I get the original state value, not the updated one. Same in the React Developer Tools, the state doesn’t update there. I even tried to return true
in the shouldComponentUpdate()
method but it didn't help.
Here is a simplified example:
var MyComponent = React.createClass({
getInitialState() {
return { myState: "value0" };
},
componentWillReceiveProps(nextProps){
if(this.state.myState != nextProps.myProp){
this.setState({
myState: nextProps.myProp
});
}
},
render: function() {
console.log("OK - up to date myState =",this.state.myState);
return (
<div>NOK - original state instead of updated one: {this.state.myState}</div>
);
}
});
ReactDOM.render(<MyComponent myProp={"myProps"} />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Would you have any explanations why the value of myState
before return
in the render
function is correct whereas the one after return
is not?