[英]unexpected react component state value change
I am trying to update the state
value but first I have loaded it in another var
and after changes made on the new var
it is going to setState
and update the original state
value. 我试图更新
state
值,但首先我已经在另一个装好了var
和新所做的更改后var
它要setState
和更新原有的state
值。 but unexpectedly changes made to the temp var
already changes the component
state
value! 但是意外地对temp
var
更改已经更改了component
state
值!
var postData = this.state.postData;
postData.likes = postData.likes + 1;
console.log(postData.likes, this.state.postData.likes);
the console.log
values: (1, 1) (2, 2) ... console.log
值:(1、1)(2、2)...
Since postData
is an object, don't save it directly in another variable since that will create a reference to the one in the state, not a copy. 由于
postData
是一个对象,因此请勿将其直接保存在另一个变量中,因为这将创建对该状态的引用,而不是副本。 And if it's a reference, changing one will change the other cos they're both pointing to the same object. 如果是参考,更改一个将更改它们都指向同一对象的其他余弦。
Make a copy of it first" 首先复制它”
var postData = Object.assign({}, this.state.postData)
and then change it. 然后更改它。 Then when you're done, use
setState({postData})
然后,完成后,使用
setState({postData})
you should never ever mutate state, always use setState, and for copying object user spread notation "..." 您永远都不应更改状态,而应始终使用setState,并且要复制对象用户的传播符号“ ...”
this.setState(((prevState) => ({
postData:{
...prevState.postData,
likes: prevState.postData.likes + 1,
}
});
You can also use ES2018 spread notation like var postData = {...this.state.postData};
您也可以使用ES2018传播符号,例如
var postData = {...this.state.postData};
to clone the object and manipulate it before assigning back to state. 复制对象并对其进行操作,然后再分配回状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.