[英]State mutation in React - need an explanation
I'm trying to understand something about React's state, deep copying of objects in JavaScript and non-mutations in functional programming in general and feel very confused at the moment due some example I ran into.我试图了解 React 的 state、JavaScript 中对象的深度复制以及函数式编程中的一般非突变,并且由于我遇到了一些示例,我现在感到非常困惑。 It's better to show one time rather to explain a thousand times, so:
最好显示一次而不是解释一千次,所以:
let arr = [
{
id: "a1",
data: [
{id: "a1b1", value: "value of a1b1"},
{id: "a1b2", value: "value of a1b2"},
]
},
{
id: "a2",
data: [
{id: "a2b1", value: "value of a2b1"},
{id: "a2b2", value: "value of a2b2"},
]
}
]
let arr2 = [...arr]
let new1 = arr2.find(item => item.id === "a2")
let new2 = new1.data.find(item => item.id === "a2b2")
new2.id = '4'
Now, because the ...
operator doesn't deep copy arr
, the arr
will be mutated as well as the arr2
in terms of modifying the new2.id
.现在,因为
...
运算符不深复制arr
,所以arr
将与arr2
一样在修改new2.id
方面发生突变。
But in React, even if I do the same thing, but with arr
being a state, the state won't get mutated... Can anyone please explain to me why this is happening and what is the appropriate way to deal with cases like this(should I deep copy, should I do something else instead?)但是在 React 中,即使我做同样的事情,但
arr
是 state,state 不会发生突变......谁能向我解释为什么会发生这种情况以及处理类似情况的适当方法是什么这个(我应该深拷贝,我应该做其他事情吗?)
** Just to be more clear here, I of course do setState when I update the state and follow the React rules ** 在这里更清楚一点,当我更新 state 并遵循 React 规则时,我当然会执行 setState
react does not work on deep reference comparison. react 不适用于深度参考比较。 So, the moment you change the reference by doing
[...arr]
react considers it a change and updates everything dependent on it.因此,当您通过执行
[...arr]
更改引用时,react 将其视为更改并更新依赖于它的所有内容。
Also, as you mentioned that react state will not be mutated;另外,正如您提到的,反应 state 不会发生突变; I do not agree with it.. it will be mutated.
我不同意它..它会变异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.