在redux中更新嵌套对象的正确方法是什么?



我正在阅读这个redux文档。https://redux.js.org/usage/structuring-reducers/immutable-update-patterns。

请参阅下面的代码

function insertItem(array, action) {
return [
...array.slice(0, action.index),
action.item,
...array.slice(action.index)
]
}

他们正在使用slice方法来更新状态,但是如果呢状态如下图

const state = [{name:"x1",obj:{}},{name:"x2",obj:{}},{name:"x3",obj:{}}];
let y = {...state.slice(1)};
console.log(state[1]['obj'] === y[0]['obj']) // true
console.log(state[2]['obj'] === y[1]['obj']) // true 

是否可以以这种方式更新状态。或者这是错误的,因为我们直接更新状态,我们可以在console.log中看到我们的新状态仍然指向旧状态嵌套对象引用。或者在创建新状态时复制旧状态参考也是可以的。不会引起任何问题。

我在stackoveflow上看到一个问题。我评论了这个解决方案。这也是在引用旧状态。

在react-redux中添加对象到嵌套数组

let state = {
items : {
deepItem  :[1, 2, 2],
reallyDeepItem: {
a : [1,2,3],
b : ['a', 'c']
}
}
};
let x = {
...state,
items : {
...state.items,
deepItem : state.items.deepItem.concat(3)
}
}

console.log(x.items === state.items) // false
console.log(x.items.reallyDeepItem === state.items.reallyDeepItem) // true (still pointing the old reference ) 
console.log(x.items.deepItem === state.items.deepItem) //false

我知道我们可以使用Immerjs和reduxtool kit,但我想了解如何正确更新不可变状态。

这个链接解释了这个问题。https://catwolf.org/qs?id=3f201d2d da9f - 4019 - 88 - ab - 566 a765b7835& x = y

常见的Redux误解:需要深度克隆状态。现实:如果内部的东西没有改变,保持它的引用不变!下面是文档链接。https://redux.js.org/faq/performance do-i-have-to-deep-clone-my-state-in-a-reducer-isnt-copying-my-state-going-to-be-slow

相关内容

最新更新