繁体   English   中英

更新ngrx state的问题

[英]Trouble with updating ngrx state

我有一个像这样的ngrx state:

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'}]
}

我有一个 function 减速器,它只需要更新任务数组的某些属性。

动作 object 包含一个属性任务,它是一个 object ,它只包含我需要编辑的属性,以及要匹配到数组中的 id。 这是 function 购买我收到错误,因为 object 是只读的。

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

尝试这个:

 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 并在返回 state 时将companyTasks应用于tasks

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

 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, }, }; } ),

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM