当我使用Chrome控制台检查render
方法中组件的状态时,我会获得最新的状态值。
但是,当我在div
中显示此状态时,我得到原始状态值,而不是更新的状态值。在React Developer Tools中,状态不会在那里更新。我甚至试图在true
方法中返回shouldComponentUpdate()
,但它没有帮助。
这是一个简化的例子:
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>
你有没有解释为什么在myState
函数中return
之前render
的值是正确的而return
之后的值不是?
使用componentWillMount()
而不是构造函数为我工作