本文介绍了在Redux中,是否有必要做深拷贝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的对象是 action.data 有一个嵌套对象 address

The below object is action.data has a nested object address

{
    name: 'Ben',
    address: {
        country: 'Australia',
        state: 'NSW'
    }
}

如何在reducer中处理?

How should I handle it in the reducer?

const rootReducer = (state = initState, action) {
    switch(action.type) {
        switch RECEIVE_DATA:
            return {...state, data: action.data}
    }
}

我可以像上面那样做吗?我只是将整个对象分配给 data 而无需复制?

Can I do it as above? that I just assign the whole object to data without copying?

const rootReducer = (state = initState, action) {
    switch(action.type) {
        switch RECEIVE_DATA:
            const address = {...action.data.address}
            const data = {...action.data, address}
            return {...state, data}
    }
}

或者我应该做一个对象的深层副本并将其分配给data?谢谢

Or should I do a deep copy of the object and assign it to data?thanks

推荐答案

正确"处理嵌套数据更新的方法是使用多个浅拷贝,每个嵌套级别一个.根据您的第一个示例,创建一个仅完全替换一个字段的新对象当然也可以.

The "correct" way to handle updates of nested data is with multiple shallow copies, one for each level of nesting. It's also certainly okay to create a new object that just replaces one field completely, per your first example.

请参阅关于不可变更新模式的 Redux 文档部分有关如何正确执行不可变更新的一些信息,以及有关 深度克隆.

See the Redux docs section on Immutable Update Patterns for some info on how to properly do immutable updates, and also the Redux FAQ entry regarding deep cloning.

这篇关于在Redux中,是否有必要做深拷贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 15:56