【问题标题】:ngrx - update single item in a list of itemsngrx - 更新项目列表中的单个项目
【发布时间】:2017-05-04 05:03:08
【问题描述】:

我有一些以下应用程序状态树:

AppState
{
    MyPage1 - MyList - MyItem[]
    MyPage2 - MySubPage - MyList - MyItem[]
    MyPage3 - MyItem   //can be stand-alone as well
}

所以,我在页面上有一个项目列表。我通过向 MyList 减速器分派一个动作来加载这个列表。加载项目后,它们将作为输入传递给 MyListComponent,从而相应地创建具有相应输入的 MyItemComponents。 MyItemComponent 也可以是独立的。所以,它并不总是依赖于 MyList。

问题是每个 MyItems 都有自己的操作(例如,可以被喜欢或编辑)。在这种情况下,我目前被困在哪里以及应该采取什么行动。如何确定更新了哪些项目以及应该更新哪个列表。

当用户更新列表中的一项时,操作流程是什么?

还有 - 如果我直接更改其中一个 MyItem 是否会检测到 MyList 的状态变化?

我可能想到的场景是(同时对 MyItem 本身进行所有适当的操作)向 MyList 添加额外的操作 - 例如:

updateItem(payload: 
    {
        updateType, //e.g. like, edit, delete
        data,       //data needed to make an update
        itemId      //index in the MyItem array
    })

然后,不知何故,我从 MyList 向数组中的指定 MyItem 触发另一个动作,item 触发适当的动作来更新它自己的状态(通过@Effect 更新) 如果更新成功,则会触发一个新操作来更新列表。

说实话,这一切似乎都非常冗长和模糊。甚至不确定如何在实践中实施。真的需要有经验的人的建议。

附言 我应该提一下,所有数据都是从 REST api 获取和发送回的。

编辑: 如果遵循Comprehensive Introduction to @ngrx/store 的方法,应用程序将具有重复动作的音调(每个容器 - MyList - 将重复来自 MyItem 的所有动作)。是否有更适合我的情况的方法?

【问题讨论】:

  • 赞成,好问题!

标签: angular redux action store ngrx


【解决方案1】:

做到这一点的方法是有一个处理状态树子部分的子减速器。

如果您需要将操作发送到数组中的单个项目,您可以将所有这些操作传递给处理单个项目的子减速器。

这是一个新闻项目的例子,它有 cmets。 我希望它能把事情弄清楚一点。

import { Action } from '@ngrx/store';
import { AppState } from '../reducer';
import { NewsItem } from './news.model';
import * as newsActions from './news.actions';

export interface NewsState {
  readonly loading: boolean;
  readonly entities: NewsItem[];
}

export interface AppStateWithNews extends AppState {
  readonly news: NewsState;
}

const initialState: NewsState = {
  loading: false,
  entities: [],
};

const newsItemReducer = (newsItem: NewsItem, action: newsActions.NewsActionTypes): NewsItem => {

  switch (action.type) {
    case newsActions.Types.UPDATE:
    case newsActions.Types.REMOVE:
    case newsActions.Types.COMMENT_CREATE:
    case newsActions.Types.COMMENT_REMOVE:
      return Object.assign({}, newsItem, {
        action: true
      });

    case newsActions.Types.UPDATE_SUCCESS:
      return Object.assign({}, action.payload, {
        action: false
      });

    case newsActions.Types.COMMENT_CREATE_SUCCESS:
      return Object.assign({}, newsItem, {
        action: false,
        comments: [action.payload.comment, ...newsItem.comments]
      });

    case newsActions.Types.COMMENT_REMOVE_SUCCESS:
      return Object.assign({}, newsItem, {
        action: false,
        comments: newsItem.comments.filter(i => i.id !== action.payload.commentId)
      });

    default:
      return newsItem;
  }
};

export const newsReducer = (state: NewsState = initialState, action: newsActions.NewsActionTypes): NewsState => {

  switch (action.type) {
    case newsActions.Types.LIST:
      return Object.assign({}, state, { loading: true });

    case newsActions.Types.LIST_SUCCESS:
      return {
        loading: false,
        entities: action.payload
      };

    case newsActions.Types.CREATE_SUCCESS:
      return Object.assign({
        loading: false,
        entities: [action.payload, ...state.entities]
      });

    case newsActions.Types.REMOVE_SUCCESS:
      return Object.assign({
        loading: false,
        entities: state.entities.filter(newsItem => newsItem !== action.payload)
      });

    // Delegate to newsItemReducer
    case newsActions.Types.UPDATE:
    case newsActions.Types.UPDATE_SUCCESS:
    case newsActions.Types.COMMENT_CREATE:
    case newsActions.Types.COMMENT_CREATE_SUCCESS:
    case newsActions.Types.COMMENT_REMOVE:
    case newsActions.Types.COMMENT_REMOVE_SUCCESS:
      return Object.assign({}, state, {
        entities: state.entities.map(newsItem => {
          // Only call sub reducer if the incoming actions id matches
          if (newsItem.id === (action.payload.newsItem || action.payload).id) {
            return newsItemReducer(newsItem, action);
          }
          return newsItem;
        })
      });

    default:
      return state;
  }

};

看看如何在这里调用这些是 news.actions。

import { Action } from '@ngrx/Store';
import { NewsItem } from './news.model';
import { Response } from '@angular/http';

export const Types = {
  LIST: '[News] List',
  LIST_SUCCESS: '[News] List Success',
  LIST_ERROR: '[News] List ERROR',

  CREATE: '[News] Create',
  CREATE_SUCCESS: '[News] Create Success',
  CREATE_ERROR: '[News] Create Error',

  UPDATE: '[News] Update',
  UPDATE_SUCCESS: '[News] Update Success',
  UPDATE_ERROR: '[News] Update Error',

  REMOVE: '[News] Remove',
  REMOVE_SUCCESS: '[News] Remove Success',
  REMOVE_ERROR: '[News] Remove Error',

  COMMENT_CREATE: '[News] Comment Create',
  COMMENT_CREATE_SUCCESS: '[News] Comment Create Success',
  COMMENT_CREATE_ERROR: '[News] Comment Create Error',

  COMMENT_REMOVE: '[News] Comment Remove',
  COMMENT_REMOVE_SUCCESS: '[News] Comment Remove Success',
  COMMENT_REMOVE_ERROR: '[News] Comment Remove Error',
};

/**
 * List
 */
export class List implements Action {
  type = Types.LIST;
  constructor(public payload?: any) {}
}
export class ListSuccess implements Action {
  type = Types.LIST_SUCCESS;
  constructor(public payload: NewsItem[]) {}
}
export class ListError implements Action {
  type = Types.LIST_ERROR;
  constructor(public payload: Response) {}
}

/**
 * Create
 */
export class Create implements Action {
  type = Types.CREATE;
  constructor(public payload: NewsItem) {}
}
export class CreateSuccess implements Action {
  type = Types.CREATE_SUCCESS;
  constructor(public payload: NewsItem) {}
}
export class CreateError implements Action {
  type = Types.CREATE_ERROR;
  constructor(public payload: Response) {}
}

/**
 * Update
 */
export class Update implements Action {
  type = Types.UPDATE;
  constructor(public payload: NewsItem) {}
}
export class UpdateSuccess implements Action {
  type = Types.UPDATE_SUCCESS;
  constructor(public payload: NewsItem) {}
}
export class UpdateError implements Action {
  type = Types.UPDATE_ERROR;
  constructor(public payload: Response) {}
}

/**
 * Remove
 */
export class Remove implements Action {
  type = Types.REMOVE;
  constructor(public payload: NewsItem) {}
}
export class RemoveSuccess implements Action {
  type = Types.REMOVE_SUCCESS;
  constructor(public payload: NewsItem) {}
}
export class RemoveError implements Action {
  type = Types.REMOVE_ERROR;
  constructor(public payload: Response) {}
}

/**
 * Create Comment
 */
export class CommentCreate implements Action {
  type = Types.COMMENT_CREATE;
  payload: {
    newsItem: NewsItem,
    comment: string
  };

  constructor(newsItem: NewsItem, comment: string) {
    this.payload = {
      newsItem,
      comment
    };
  }
}
export class CommentCreateSuccess implements Action {
  type = Types.COMMENT_CREATE_SUCCESS;
  payload: {
    newsItem: NewsItem,
    comment: string
  };
  constructor(newsItem: NewsItem, comment: string) {
    this.payload = {
      newsItem,
      comment
    };
  }
}
export class CommentCreateError implements Action {
  type = Types.COMMENT_CREATE_ERROR;
  constructor(public payload: Response) {}
}

/**
 * Remove Comment
 */
export class CommentRemove implements Action {
  type = Types.COMMENT_REMOVE;
  payload: {
    newsItem: NewsItem,
    commentId: string
  };

  constructor(newsItem: NewsItem, commentId: string) {
    this.payload = {
      newsItem,
      commentId
    };
  }
}
export class CommentRemoveSuccess implements Action {
  type = Types.COMMENT_REMOVE_SUCCESS;
  payload: {
    newsItem: NewsItem,
    commentId: string
  };
  constructor(newsItem: NewsItem, commentId: string) {
    this.payload = {
      newsItem,
      commentId
    };
  }
}
export class CommentRemoveError implements Action {
  type = Types.COMMENT_REMOVE_ERROR;
  constructor(public payload: Response) {}
}

export type NewsActionTypes =
    List
  | ListSuccess
  | ListError
  | Create
  | CreateSuccess
  | CreateError
  | Update
  | UpdateSuccess
  | UpdateError
  | Remove
  | RemoveSuccess
  | RemoveError
  | CommentCreate
  | CommentCreateSuccess
  | CommentCreateError
  | CommentRemove
  | CommentRemoveSuccess
  | CommentRemoveError;

【讨论】:

  • 谢谢!你的回答很有帮助,我喜欢你的代码有多干净
  • 只是在newsReducer中做所有这些只是关注点分离+模块化代码之间的区别,还是有实际必要让ngrx/store知道正在应用的单个项目reducer? IE。如果您将newsReducer 中的所有newsItemReducer 组合在一起,然后只执行state.map 并返回更新的newsState,ngrx 的行为会有所不同吗?
  • 只是为了分离关注点。而且推理单个项目比推理集合更容易。
  • @LeonRadley 我正在使用带有'createReducer'和'on'的ngrx8的新语法,有没有办法以这种新语法将动作传递给下一个reducer?谢谢
  • @RenjithP.N.对不起,我不知道,我已经有一段时间没有使用ngrx了。希望你在其他地方找到你的答案:)
猜你喜欢
  • 1970-01-01
  • 2017-07-21
  • 2016-12-21
  • 2013-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
相关资源
最近更新 更多