如何更新或删除ngrx实体中的嵌套对象?

时间:2018-01-23 18:14:56

标签: javascript angular rxjs ngrx ngrx-entity

如何更新或删除ngrx实体中的嵌套对象,例如我想删除第一个具有19个id的元素(charter.entities.scopes.data),如我在ngrx商店中的bellow存储的json对象中所示

 charter: {
      ids: [
        1
      ],
      entities: {
        '1': {
          id: 1,
          projectName: 'Some Project',
          projectCode: '899',
          projectUniqueCode: '674a9596-50ee',
          projectStatus: 'construction',
          budgetCode: 'CC34',
          projectTypeOne: 'Goods',
          projectTypeTwo: 'New',
          donorName: 'Elza Hills',
          scopes: {
            data: [
              {
                id: 19,
                module: 'Miss Cassandra Cartwright I',
                description: 'In tempore quia asperiores aut ea cum optio minima nemo est et aspernatur est repudiandae voluptas ipsum.',
                time: '2018-01-23 15:37:36'
              },

              {
                id: 43,
                module: 'Leanne Douglas',
                description: 'Occaecati facere eligendi esse esse nostrum in et vitae assumenda molestias omnis quis sit qui aut omnis est.',
                time: '2018-01-23 15:37:36'
              },
            ]
          },
          assumptions: {
            data: [
              {
                id: 29,
                assumption: 'Doloremque quo nihil minima ad optio perspiciatis asperiores debitis mollitia at debitis porro quia nam accusantium illo consequatur labore cum.',
                comments: 'Inventore ut pariatur id laboriosam recusandae soluta quo sunt impedit aut velit.'
              },
              {
                id: 164,
                assumption: 'Dolores quam aut possimus sint fugiat natus quos quaerat saepe facilis harum molestiae.',
                comments: 'Cumque quis magni illo dolore quas nam officiis dolores enim soluta doloribus in sed eum ut sunt.'
              },
            ]
          },

减速器

export interface State extends EntityState<ProjectsCharter> {
  isLoading: boolean;
  isLoaded: boolean;
  selectedProjectsId: any;
}

export const adapter: EntityAdapter<ProjectsCharter> = createEntityAdapter({
  selectId: (state: ProjectsCharter) => state.id,
  sortComparer: false
});

export const initialState = adapter.getInitialState({
  isLoading: false,
  isLoaded: false,
  selectedProjectsId: null
});

export function reducer(state = initialState, action: CharterActions) {
  switch (action.type) {
    case CharterActionTypes.loadCharterSuccess:
      return {
        ...adapter.addOne(action.payload['data'], state),
        isLoading: false,
        isLoaded: true
      };
    case CharterActionTypes.updateScopeOnParent:
      const scopeEntity = { ...state.entities[action.payload.param] };
      scopeEntity.scopes.data = scopeEntity.scopes.data.map(item => {
        if (item.id === action.payload.id) {
          item.module = action.payload.module;
        }
        return item;
      });

      return {
        ...adapter.updateOne(scopeEntity, state)
      };
    default:
      return {
        ...state
      };
  }
}

我可以使用这个reducer更新和修改nestad对象,但问题是1-它有点复杂,并且还在编译时在终端中显示error TS2339: Property 'map' does not exist on type 'Scope'. Argument of type '{ id: string; projectName: string; projectStatus: string; projectCode: string; projectUniqueCode:...' is not assignable to parameter of type 'Update<ProjectsCharter>'.

3 个答案:

答案 0 :(得分:5)

我强烈建议您更换商店并将其标准化。看看这里:https://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html

使用这种方法,您将拥有不那么复杂的减速器,如此处所述 https://redux.js.org/docs/recipes/reducers/UpdatingNormalizedData.html

以这种方式塑造商店,您将不得不建造一个复杂的减速器。

答案 1 :(得分:2)

根据我的逻辑,以下减速器mods至少应该消除 TS2339 错误。

这一位

  

类型'{id:string; projectName:string; projectStatus:string; projectCode:string; projectUniqueCode:...'不能分配给'Update'类型的参数

只是告诉你(以非有用的方式)adapter.updateOne需要第一个模式{ id, changes }的参数,但你只是给它changes


export function reducer(state = initialState, action: CharterActions) {
  switch (action.type) {

    case CharterActionTypes.loadCharterSuccess:
      ...

    case CharterActionTypes.updateScopeOnParent:

      const id = action.payload.param;
      const entities = {...state.entities};
      const original = entities[id];

      const newScopes = original.scopes.data.map(item => {
        if (item.id === action.payload.id) {
          item.module = action.payload.module;
        }
        return item;
      });
      const changes = { scopes: { data: newScopes }} // Partial<ProjectsCharter>

      return {
        ...adapter.updateOne({ id, changes }, state)
      };
    }

    default:
      ...
  }
}

答案 2 :(得分:0)

让我以此开头为前提,说理想的解决方案是使用normalizr之类的东西来规范您的实体。就是说,这是一个对我有用的解决方案:

  1. 对状态对象进行深层克隆
  2. 在克隆的对象上使用Javascript delete方法
  3. 将此新对象作为新状态传递

因此,假设您的状态看起来像这样:

{
  entities: {
   '1': {
     prop1: 'val1',
     nested: {
      '1': {
        prop1: 'val1'
      },
      '2': {
        prop2: 'val2'
      }
    }
  }
}

如果您的目标是删除entities[1].nested[1],只需使用以下代码(请注意,我正在使用lodash library):

import * as _ from 'lodash'

on(Actions.sampleDeleteAction, (state) => {
  const clonedState = _.cloneDeep(state);

  delete clonedState.entities[1].nested[1];

  return { ...clonedState };
}

很显然,您希望将props添加到操作中,其中包含要删除的必要索引值,而不是像示例entities[1].nested[1]中那样显式使用索引。