【发布时间】: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 操作中传递一个只有单个值的道具来更新对象的单个属性是不正确的吗?
【问题讨论】:
-
我建议你看看ngrx-immer,它使这种操作变得简单。 github.com/timdeschryver/ngrx-immer
标签: javascript angular redux ngrx