[英]Why my react state became not-immutable?
In javascript objects are mutable. 在javascript中,对象是可变的。
For example if 例如,如果
var a = {"something": 1}
and if you assign it to another variable b
and if you change its value, the value of object a
is also changed 如果将其分配给另一个变量
b
并更改其值,则对象a
的值也将更改
var b = a;
b.something = 2;
console.log(b);
console.log(a);
//output {"something": 2}
both will print {"something": 2}. 两者都将打印{“ something”:2}。 The value in a is also changed.
a中的值也被更改。
Similarly in your code you are directly assigning the state value in line number 61
and mutating it in line number 62
. 同样,在您的代码中,您直接在第
61
行中分配状态值,并在第62
行中对其进行修改。
So better way is to use 所以更好的方法是使用
let newOptions = {...this.state.newOptions };
or 要么
let newOptions = Object.assign({},this.state.newOptions}
This will create new object. 这将创建新对象。
React state is mutable, so you can update react state directly. React状态是可变的,因此您可以直接更新React状态。 But it is recommended not to mutate react state due to multiple reasons.
但是由于多种原因,建议不要改变反应状态。 One of the reasons is, if you do
this.state.count = 3
, react DOM will behave in an unpredictable manner such as overwriting data and not re-rendering. 原因之一是,如果执行
this.state.count = 3
,则反应DOM将以不可预测的方式运行,例如覆盖数据而不重新渲染。 Performance tuning is another reason. 性能调整是另一个原因。
React on calling setState()
will call the render
method in some near future which will cause the DOM to be updated with new values. 调用
setState()
反应将在不久的将来调用render
方法,这将导致DOM被新值更新。
the state does mutate in react. 国家的反应确实发生了变化。 and u should be very careful that u don't override it like that or you will encounter unexpected result.
您应该非常小心,不要像这样覆盖它,否则您将遇到意想不到的结果。 it is always best to copy your state into another object, then change its properties as u like and after you are done use set state to set set your object state as copied object.
始终最好将状态复制到另一个对象,然后根据需要更改其属性,并在完成后使用set state设置将对象状态设置为复制对象。 you can use Object.Assign or spread operator for this.
您可以为此使用Object.Assign或散布运算符。 spread operator is easier when you are using Arrays.
使用数组时,散布运算符更容易。
this.state = {
myObj : {propA: "A" , propB: "B"};
}
then at some point you want to change it 然后在某个时候你想改变它
let myObj = this.state.myObj;
let copyMyObj = {...myObj};
copyMyObj.propA = "C";
this.setState({
myObj: copyMyObj
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.