redux复杂对象不会触发更新

时间:2019-09-05 13:57:21

标签: redux react-redux

大家好,我正在尝试更新具有4个嵌套级别的redux对象。我使用Object.Assign()和redux开发工具显示了差异。但是由于某些原因,我订阅的组件未将其标记为已更改。我想我做的不对,但是我多次检查,看不到我做错了什么。

我的redux减速器:

import {
    FETCH_SETTINGS,
    FETCH_SETTINGS_SUCCESS,
    FETCH_SETTINGS_FAILURE,
    UPDATE_USER_SETTINGS,
    UPDATE_USER_SETTINGS_FAILURE,
    UPDATE_USER_SETTINGS_SUCCESS
} from './actions';

const initialState = {
    settingsError: '',
    settingsLoading: false,
    settings: [],
    updateUSerSettingsLoading: false
};

const settingsReducer = (state = initialState, action) => {
    switch (action.type) {

case UPDATE_USER_SETTINGS_SUCCESS: {
            const newUserSettings = action.payload.settings.settings;

            let currentState = Object.assign({}, state);
            console.log('equals?', state === currentState);
            const newSettingsArray = currentState.settings.settings.userSettings.map(
                setting => {
                    if (setting.key === 'Language') {
                        // update the current setting with a particular key to the newSetting value
                        for (let newSetting of newUserSettings) {
                            if (newSetting.key === 'Language') {
                                const setSetting = Object.assign(
                                    {},
                                    { key: newSetting.key, value: newSetting.value }
                                );
                                return setSetting;
                                break;
                            }
                            return newSetting;
                        }
                        return setting;
                    }
                    return setting;
                }
            );
            currentState.settings.settings.userSettings = newSettingsArray;

            return {
                ...state,
                settings: currentState.settings
            };
        }

default: {
        return state;
    }
}
};

export default settingsReducer;

t-redux

非常感谢您的帮助。干杯!

1 个答案:

答案 0 :(得分:0)

我找到了一个不错的解决方案,使我无法重写整个设置部分。我们必须确保每个对象都是不可变的,如果不是redux不会显示更改。因此,在我的情况下,这可行:

return {
            ...state,
            settings: {
                ...state.settings,
                settings: {
                    ...state.settings.settings,
                    userSettings: newSettingsArray
                }
            }
        };

但是将来我会尝试使减速器保持平稳!