在我的Angular2应用程序中,我使用ngrx来管理状态,因此,当我从服务器接收数据时,我将一个操作分派(dispatch)给reducer。

MyExampleReducer.ts:

export const Reviews: ActionReducer<any> = (state: any[] = [], action: Action) => {
switch (action.type) {
        case GET_REVIEWS:
            return action.payload;
        case ADD_REVIEW :
            return [...state, {review : action.payload, replays : []}];
        case UPDATE_REVIEW:
            return  '' // return what ?
        case DELETE_REVIEW:
            return state.filter(item => {
                return item.id !== action.payload.id;
            });
        default:
            return state;
    }
};

问题是当我必须更新评论数组中的项目时,以redux方式执行的最佳方法是什么?

最佳答案

您可以使用map返回一个数组,该数组具有与更新的操作相对应的元素:

export const Reviews: ActionReducer<any> = (state: any[] = [], action: Action) => {
  switch (action.type) {
    case ADD_REVIEW:
      return [...state, { review: action.payload, replays: [] }];
    case UPDATE_REVIEW:
      return state.map(item => item.id === action.payload.id ? { review: action.payload, replays: [] } : item);
    case DELETE_REVIEW:
      return state.filter(item => item.id !== action.payload.id);
    default:
      return state;
    }
}

另外,您可以通过使用评论缩减器执行ADD_REVIEWUPDATE_REVIEW操作来简化评论缩减器-评论缩减器仅关注管理评论列表,而不关注评论本身:
import { reviewReducer } from '...';
export const Reviews: ActionReducer<any> = (state: any[] = [], action: Action) => {
  switch (action.type) {
    case ADD_REVIEW:
      return [...state, reviewReducer(undefined, action)];
    case UPDATE_REVIEW:
      return state.map(item => item.id === action.payload.id ? reviewReducer(item, action) : item);
    case DELETE_REVIEW:
      return state.filter(item => item.id !== action.payload.id);
    default:
      return state;
    }
}

关于Angular 2 Ngrx : what is the proper way to immutably update an array of objects in reducers?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41572559/

10-12 12:25