【问题标题】:Trouble with updating ngrx state更新ngrx状态的问题
【发布时间】:2021-04-03 09:11:48
【问题描述】:

我有一个这样的ngrx状态:

company: {
  id: '1',
  name: 'myCompany',
  task: [{id: 1, name: 'task1', date: '20-01-2021', endDate: '22-01-2021'}, {id: 2, name: 'task2', date: '23-01-2021', endDate: '24-01-2021'}]
}

我有一个函数 reducer,它只需要更新任务数组的某些属性。

action 对象包含一个属性任务,它是一个仅包含我需要编辑的属性以及要匹配到数组中的 id 的对象。这是因为对象是只读的,所以我得到了错误的函数。

 on(
CompanyAction.editTask,
(state, action): CompanyState => {
  const index = state.company.tasks.findIndex(el => el.id === action.taskId);

  // here I want to update the task that I've edited But I got error
  state.company.tasks[index] = { ...state.company.tasks[index], ...action.task };
  return {
    ...state,
    company: {
      ...state.company,
      tasks: state.company.tasks,
    },
  };
}),

有什么建议吗?

附言

我尝试过这种方式,但如果在操作中我只有一个道具示例名称:字符串,我会这样做:

on(
  CompanyAction.editTask,
  (state, action): CompanyState => {
    const newTasks = state.company.tasks.map(item => {
      if (item.id === action.taskId) {
        item.name = action.name  // this gives me a read only error
      } else {
        return item;
      }
    })
    return {
      ...state,
      company: {
        ...state.company,
        tasks: newTasks,
      },
    };
  }),

它给了我同样的只读错误。

在 ngrx 操作中传递一个只有单个值的道具来更新对象的单个属性是不正确的吗?

【问题讨论】:

标签: javascript angular redux ngrx


【解决方案1】:

试试这个:

 on(
CompanyAction.editTask,
(state, action): CompanyState => {
  const index = state.company.tasks.findIndex(el => el.id === action.taskId);
  
  let companyTasks = {...state.company.tasks};
  let editingTask = companyTasks[index];
  companyTasks = companyTasks.filter((task, idx) => {return idx !== index});
  editingTask = {...editingTask, ...action.task};
  companyTasks.push(editingTask);
  
  return {
    ...state,
    company: {
      ...state.company,
      tasks: companyTasks,
    },
  };
}

首先在找到所需任务的索引后,创建一个名为companyTasks的所有任务的副本。

然后根据索引 (editingTask) 选择任务并将其从 companyTasks 中删除。编辑后将其推送到companyTasks。并在返回状态将companyTasks 应用到tasks

【讨论】:

    【解决方案2】:

    无法测试,但你可以试试这个。

    on(
      CompanyAction.editTask,
      (state, action): CompanyState => {
        const newTasks = state.company.tasks.map(item => {
          if (item.id === action.taskId) {
            // write code for what you wnat to do when id matches
          } else {
            return item;
          }
        })
        return {
          ...state,
          company: {
            ...state.company,
            tasks: newTasks,
          },
        };
      }
    ),

    【讨论】:

    • 我尝试过,但如果我尝试以这种方式编辑属性,则进入 if:item.name = action.name....它给了我一个错误。我不想创建卷影副本...
    猜你喜欢
    • 2022-06-18
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    相关资源
    最近更新 更多