Javascript 更新ngrx状态时出现问题

Javascript 更新ngrx状态时出现问题,javascript,angular,redux,ngrx,Javascript,Angular,Redux,Ngrx,我的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'}] } 我有一个函数缩减器,只需要更新任务数组的一些属性 action对象包含一个属性任务,该任务只包含我

我的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'}]
}
我有一个函数缩减器,只需要更新任务数组的一些属性

action对象包含一个属性任务,该任务只包含我需要编辑的属性和要匹配到数组中的id。这是函数buy I Get error,因为对象是只读的

 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,
    },
  };
}),
有什么建议吗

附言

我试过这样做,但如果在动作中我只有一个道具示例名称:string,我会这样做:

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操作中传递一个只有一个值的道具来更新对象的单个属性是不正确的吗?

无法测试它,但您可以尝试此操作

on(
CompanyAction.editTask,
(状态、操作):CompanyState=>{
const newTasks=state.company.tasks.map(项=>{
if(item.id==action.taskId){
//编写代码,说明当id匹配时您将执行的操作
}否则{
退货项目;
}
})
返回{
……国家,
公司:{
…国营公司,
任务:新任务,
},
};
}
),
试试这个:

on(
CompanyAction.editTask,
(状态、操作):CompanyState=>{
const index=state.company.tasks.findIndex(el=>el.id==action.taskId);
让companyTasks={…state.company.tasks};
让editingTask=companytask[index];
companyTasks=companyTasks.filter((任务,idx)=>{return idx!==index});
editingTask={…editingTask,…action.task};
companytask.push(编辑任务);
返回{
……国家,
公司:{
…国营公司,
任务:公司任务,
},
};
}
首先,在找到所需任务的索引后,创建名为
companyTasks
的所有任务的副本


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

,我建议您查看ngrx immer,它使此类操作变得简单。如果我尝试以这种方式编辑属性,我尝试了if:item.name=action.name…它给了我一个错误。我不想创建卷影副本。。。