首页 > 解决方案 > 使用扩展运算符更新不同级别的状态

问题描述

我有一个减速器状态初始化如下:

state = {
    name: ""
    authenticationObj: {
        userContactInfo: {
            billingAddress: {
                billingCountry: undefined,
                billingAddress1: undefined,
                billingAddress2: undefined,
                billingCity: undefined,
                billingPostalCode: undefined,
                billingPhoneNumber: undefined,
                billingFirstName: undefined,
                billingLastName: undefined,
                billingPersonalEmail: undefined,
                billingSelectedRegion: undefined
            },
        },
        subscriptions: [],
        fullName: "",
        subscriberDefaultPhoneNumber: ""
    }
}

现在我需要使用扩展运算符来更新状态,这就是我所拥有的工作:

case SET_SUBSC_LIST:
    state = { ...state,
        authenticationObj: { ...state.authenticationObj,
            subscriptions: action.payload.subscriptions
        }
    }

但是,如果我想更新不同级别的属性怎么办。例如,如果我需要同时更新订阅以及 billingAddress1 里面的 billingAddress1,我该如何实现呢?

标签: javascriptreactjsecmascript-6redux

解决方案


您可以使用lodash 中的合并方法而不是扩展运算符,这样更易​​于阅读。

case SET_SUBSC_LIST:
    state = _.merge(state, { authenticationObj: {
            subscriptions: action.payload.subscriptions
        }
    }

推荐阅读