Redux初始状态值变为未定义

时间:2017-06-27 06:24:59

标签: redux state

以下是我的初始默认状态值

export const parameterInitialState = {
    id: '',
    name: '',
    parameterSettings: parameterSettingsInitialState,
    parameterMediaSettings: parameterMediaSettingsInitialState,
};

export const parameterSettingsInitialState = {
    attributeId: '',
    value: '',
};

export const parameterMediaSettingsInitialState = {
    barcodeSupported: false,
    mediaTypeId: '',
    qrcodeSupported: false,
    scratchOffPINSupported: false,
};

在parameterState reducer中,我使用上面的parameterInitialState

const initialState = {
    parameterSettings: parameterInitialState,
};

export default function parameterState( state = initialState, action ) {
    switch ( action.type ) {
        case FETCH_PARAMETER_SUCCESS:{
            return { ...state,  ...action.payload };
        }

        default:
            return state;
    }
}

但我的问题是在初始状态下,对象parameterSettings和parameterMediaSettings变得未定义

1 个答案:

答案 0 :(得分:2)

更改初始状态变量的定义顺序,在给定的顺序变量parameterSettingsInitialStateparameterMediaSettingsInitialState将返回undefined。

因此,请确保首先定义子对象变量,然后定义您计划包含在其中的父对象。

    export const parameterSettingsInitialState = {
        attributeId: '',
        value: '',
    };

    export const parameterMediaSettingsInitialState = {
        barcodeSupported: false,
        mediaTypeId: '',
        qrcodeSupported: false,
        scratchOffPINSupported: false,
    };

    export const parameterInitialState = {
        id: '',
        name: '',
        parameterSettings: parameterSettingsInitialState,
        parameterMediaSettings: parameterMediaSettingsInitialState,
    };

更新了parameterSettingsInitialStateparameterMediaSettingsInitialState作为数组的答案:

    export const parameterSettingsInitialState = [{
        attributeId: '',
        value: '',
    }];

    export const parameterMediaSettingsInitialState = [{
        barcodeSupported: false,
        mediaTypeId: '',
        qrcodeSupported: false,
        scratchOffPINSupported: false,
    }];

    export const parameterInitialState = {
        id: '',
        name: '',
        parameterSettings: parameterSettingsInitialState,
        parameterMediaSettings: parameterMediaSettingsInitialState,
    };