避免物体突变 [英] Avoiding object mutation
问题描述
我正在使用React和ES6.因此,我到达了以下情况:我有一个状态,其中包含对象数组,假定a = [{id: 1, value: 1}, {id: 2, value: 2}]
处于Object A
状态,然后我通过props将Object B
(在构造函数中)副本传递给Object B
列表返回到自己的状态,并调用使用map
函数的函数,在该函数中我返回b = [{id: 1, value: 1, text: 'foo'}, {id: 2, value: 2, text: 'foo'}]
(向每个对象添加(text, value)
),因此尽管它没有使Object A
中的a
发生突变,但是
I am working with React and ES6. So I arrivied to the following case: I have an state with an array of objects suppose a = [{id: 1, value: 1}, {id: 2, value: 2}]
in the state of Object A
, then I pass the list to Object B
by props, Object B
(in the constructor) copy the list to its own state and call a function which is using map
function where I return b = [{id: 1, value: 1, text: 'foo'}, {id: 2, value: 2, text: 'foo'}]
(added (text, value)
to each object), so it though it was not mutating a
in Object A
but it was.
所以我做了一些测试:
const a = [{id: 1, value: 1}, {id: 2, value: 2}] // suppose it is in object A
addText = (list) => {
return list.map((item) => {item.text = "foo"; return item})
}
const b = addText(a) // suppose it is in object B
所以根据我的假设a !== b
,但是a
被addText
突变了,所以它们相等.
so under my assumption a !== b
, but a
was mutated by addText
, so they were equal.
在一个大型项目中,程序员会犯错误(我在这里做了!),应该如何处理这种情况,以免以这种方式使对象发生变化? (该示例尝试将a
重新设置为Object A
的state
,这是React的组件)
In a large scale project programmers make mistakes (I did here!) how it is supposed to be handled this kind of situations to avoid mutating objects in this way? (The example tries to represet a
as an state
for Object A
which is a component from React)
推荐答案
如果对对象的更改确实很浅(在对象的顶层),则可以使用Object.assign({}, oldObj, newObj)
,或者如果您使用<在babel { ...oldObj, newThing: 'thing' }
If your change to the object is really that shallow (at the top level of the object), you can use Object.assign({}, oldObj, newObj)
, or if you have the Object spread proposal enabled in babel, { ...oldObj, newThing: 'thing' }
要在团队中实施此操作,可以使用此ESLint插件 https://github.启用了no-mutation
规则的com/jhusain/eslint-plugin-immutable .
To enforce this on a team, you could use this ESLint plugin https://github.com/jhusain/eslint-plugin-immutable with the no-mutation
rule enabled.
这篇关于避免物体突变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!