使用Object.assign对对象所做的更改会使源对象发生变化 [英] Changes to object made with Object.assign mutates source object
问题描述
我的react-redux应用程序中有以下reducer代码:
I have following reducer code in my react-redux app:
case 'TOGGLE_CLIENT_SELECTION':
const id = action.payload.id;
let newState = Object.assign({}, state);
newState.list.forEach((client) => {
if (client.id == id) client.selected = !client.selected;
});
console.log(state.list[0].selected + ' - ' + newState.list[0].selected)
return newState;
如果我做对了-Object.assign创建了一个全新的对象,但是console.log显示了"false-false"的"true-true".有什么想法为什么它会这样,我该如何避免这种行为?
If I got it right - Object.assign creates brand new object, but console.log displays "true - true" of "false - false". Any thoughts why it behaves like this and how can I avoid this behavior?
推荐答案
是正确的,但这不是深层副本.
True, but it's not a deep copy.
新对象包含对旧列表的引用.
The new object contains a reference to the old list.
这是解决它的一个窍门(有人可能会说更"正确的方式):
Here's a trick to get around it (there's more "proper" ways some might say):
JSON.stringify原始.然后JSON.parse该字符串.新对象将是深层复制"(不确定在技术上是否真的是深层复制").除非您的子类型比标准的普通旧JSON可接受的东西更复杂,否则它会很好地工作.
JSON.stringify the original. Then JSON.parse that string. The new object will be a "deep" copy (not sure if that's really technically "deep copying"). It works fine unless your sub-types are something more complex than standard plain old JSON-acceptable stuff.
这篇关于使用Object.assign对对象所做的更改会使源对象发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!