8

如何更新或删除ngrx实体中的嵌套对象例如我想从(charter.entities.scopes.data)中删除第一个具有19个id的元素,如我的ngrx商店中存储的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>'.

4

3 回答 3

9

我强烈建议您更改商店并使其正常化。看看这里:https ://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html

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

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

于 2018-01-23T18:38:01.517 回答
4

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

这一点

'{ id: string; 类型的参数 项目名称:字符串;项目状态:字符串;项目代码:字符串;projectUniqueCode:...' 不可分配给“更新”类型的参数

只是告诉你(以一种无益的方式)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:
      ...
  }
}
于 2018-01-24T06:17:46.420 回答
1

让我先说理想的解决方案是使用 normalizr 之类的东西来规范化您的实体。也就是说,这是一个适合我的解决方案:

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

所以让我们假设你的状态看起来像这样:

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

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

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]

于 2020-05-28T23:36:43.283 回答