[英]Using setState in reactJs with an object always remains empty
I have this snippet that doesn't seem to be work and it is driving me insane! 我的这段代码似乎无效,这让我发疯了! Can someone please point out what I have done wrong ? 有人可以指出我做错了什么吗?
getInitialState: function () {
return {
modalUser: {},
users: []
};
},
updateModalUser: function (user) {
console.log(user);
module.React.addons.update(this.state, {
modalUser: { $set: user }
});
console.log(this.state);
},
I did try doing this originally without the addons, but I had the same result. 我确实尝试在没有插件的情况下进行此操作,但结果却相同。 ie my updateModalUser looked like: 即我的updateModalUser看起来像:
updateModalUser: function (user) {
console.log(user);
this.setState({
modalUser: user
});
console.log(this.state);
},
This output I get either way is: 我得到的输出结果是:
Object {id: 28, fname:"fred", lname:"flinstone"…}
Object {modalUser: {}, users: []}
this.setState()
is async, you need to log the state in it's callback: this.setState()
是异步的,您需要在其回调中记录状态:
updateModalUser: function (user) {
console.log(user);
this.setState({
modalUser: user
}, function() {
console.log(this.state);
})
}
More info here: https://facebook.github.io/react/docs/component-api.html#setstate 此处提供更多信息: https : //facebook.github.io/react/docs/component-api.html#setstate
您应该使用this.setState({modalUser: newObjectHere})
,这是更改组件状态的正确方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.