[英]ReactJS State not getting updated
I am updating a state from child. 我正在从孩子那里更新状态。
getInitialState : function(){
return{
VotedForTopic : false
};
},
updateVotedState:function(){
this.setState({VotedForTopic:true});
console.log(this.state.VotedForTopic)
},
I am calling updateVotedState from the child when some action is performed to change the VotedForTopic state to true.But the state is not getting updated it remains false. 当执行某些操作以将VotedForTopic状态更改为true时,我正在从孩子那里调用updateVotedState,但是该状态没有得到更新,因此仍然为false。 What could be the problem
可能是什么问题呢
You can update parent
state from child
using callback which passed to child
through props
, like this 您可以使用通过
props
传递给child
回调从child
更新parent
状态。
var Parent = React.createClass({
getInitialState: function () {
return {
VotedForTopic: false
};
},
updateVotedState: function () {
this.setState({ VotedForTopic: true });
},
render: function() {
return <div>
<p>{'Current State:: ' + this.state.VotedForTopic} </p>
<Child onUpdateVote={this.updateVotedState} />
</div>;
}
});
var Child = React.createClass({
render: function() {
return <a onClick={this.props.onUpdateVote}>updateVotedState</a>;
}
});
Does the state never update or are you relying on the console.log
? 状态永远不会更新还是您依赖
console.log
? From the docs: 从文档:
setState() does not immediately mutate this.state but creates a pending state transition.
setState()不会立即使this.state发生突变,而是创建一个挂起的状态转换。 Accessing this.state after calling this method can potentially return the existing value.
调用此方法后访问this.state可能会返回现有值。
try passing a callback to setState
: 尝试将回调传递给
setState
:
updateVotedState:function(){
var that = this;
this.setState({VotedForTopic:true}, function(){
console.log(that.state.VotedForTopic)
});
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.