NGRX REDUCER使用SAME STATE对象

时间:2019-08-22 15:05:13

标签: javascript angular typescript redux ngrx

我将重新提出问题:

得到了这两个减速器:

export function reducer1(state: State = initialState,: Actions1.Actions1);
export function reducer2(state: State = initialState,: Actions2.Actions1);

我需要那些简化器来修改相同的状态对象。

因为它们将使用相同的状态对象,所以我不能简单地将状态拆分成小块,以使新的化简器使用它们,如答案所示=> https://stackoverflow.com/a/51970052/2992476

预先感谢

1 个答案:

答案 0 :(得分:0)

在第一部分中,您已经提到将减速器拆分为小型减速器,因此我不再赘述。

第二,您可以使用NGRX/Entity来让NGRX为您处理CRUD操作,因为NGRX / Entity已经包含一些允许开发人员对状态执行CRUD操作的API,因此可以降低代码复杂度。

示例:

const userReducer = createReducer(
  initialState,
  on(UserActions.addUser, (state, { user }) => {
    return adapter.addOne(user, state)
  }),
  on(UserActions.upsertUser, (state, { user }) => {
    return adapter.upsertOne(user, state);
  }),
  on(UserActions.addUsers, (state, { users }) => {
    return adapter.addMany(users, state);
  }),
  on(UserActions.upsertUsers, (state, { users }) => {
    return adapter.upsertUsers(users, state);
  }),
  on(UserActions.updateUser, (state, { user }) => {
    return adapter.updateOne(user, state);
  }),
  on(UserActions.updateUsers, (state, { users }) => {
    return adapter.updateMany(users, state);
  }),
  on(UserActions.mapUsers, (state, { entityMap }) => {
    return adapter.map(entityMap, state);
  }),
  on(UserActions.deleteUser, (state, { id }) => {
    return adapter.removeOne(id, state);
  }),
  on(UserActions.deleteUsers, (state, { ids }) => {
    return adapter.removeMany(ids, state);
  }),
  on(UserActions.deleteUsersByPredicate, (state, { predicate }) => {
    return adapter.removeMany(predicate, state);
  }),
  on(UserActions.loadUsers, (state, { users }) => {
    return adapter.addAll(users, state);
  }),
  on(UserActions.clearUsers, state => {
    return adapter.removeAll({ ...state, selectedUserId: null });
  })
);