在 Redux reducer 中合并具有相同键的数组对象元素

Merge array object elements with same key in Redux reducer

我的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;
    }
};

电流我得到以下旧状态和新状态:

我希望新对象用数组中的相同键覆盖现有对象,我们将不胜感激

这种情况下,你需要用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 替换为对象中的任何唯一标识符。这样您就可以省略要用较新的对象替换的对象。

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

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;
}