【问题标题】:Merge array object elements with same key in Redux reducer在 Redux reducer 中合并具有相同键的数组对象元素
【发布时间】:2019-12-31 06:33:38
【问题描述】:

我的reducer如下:

    export const favorites = (state = {
    favorites: [],
    countFavorite: [],
    }, action) => {
        switch (action.type) {
            case ActionTypes.ADD_FAVORITE:
                return { ...state, favorites: action.payload };

        case ActionTypes.COUNT_FAVORITE:
            return { ...state, countFavorite: [...state.countFavorite, action.payload] };
        default:
            return state;
    }
};

当前我得到以下与旧状态和新状态:

我希望新对象用数组中的相同键覆盖现有对象,非常感谢任何帮助

【问题讨论】:

    标签: javascript react-native redux redux-reducers


    【解决方案1】:

    首先,您应该检查密钥是否存在,然后添加更多项:

    switch (action.type) {
        case ActionTypes.ADD_FAVORITE:
            return { ...state, favorites: action.payload };
    
        case ActionTypes.COUNT_FAVORITE: {
            let key = Object.keys(action.payload)[0];
            return { ...state, countFavorite: [...state.countFavorite.filter(fa => Object.keys(fa)[0] !== key), action.payload] };
        }
        default:
            return state;
    }
    

    【讨论】:

      【解决方案2】:

      在这种情况下,你需要使用Array.filter从数组中只过滤出与你的action.payload相同ID的对象,然后填写action.payload。

      应该是这样的。

      case ActionTypes.COUNT_FAVORITE:
        return { ...state, countFavorite: [ ...state.countFavorite.filter( fav => fav.id !== action.payload.id ), action.payload] };
      

      您可以将 ID 替换为对象中的任何唯一标识符。这样,您可以省略要替换为较新对象的对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多