我正在尝试更新我的redux crud表单。我正在使用不变性帮助器。 我的减速器是:
case UPDATE_TODO:
console.log("reducer todo",action.toDo,state)
return update(state, { $set: [action.toDo] })
但是没有替换特定的对象,而是将整个数组替换为一个。我在哪里做错了? 我的状态是这样:
[
{_id: "5b3d2696e099830f249dddfd", title: "hello", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
{_id: "5b3d2696e099830f249dddxe", title: "hello", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
]
,更新后应该是这样的:
[
{_id: "5b3d2696e099830f249dddfd", title: "hello", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
{_id: "5b3d2696e099830f249dddxe", title: "hello1", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
]
但是它给出的结果是这样的:
[
{_id: "5b3d2696e099830f249dddxe", title: "hello1", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
]
答案 0 :(得分:0)
您的代码未针对您要在状态下更新的特定待办事项,因此它将替换整个状态。有两种方法可以实现此目的:
1)在使用$ set方法之前,先使用Array.findIndex方法找到要更新的待办事项的索引。
const todoIndex = state.findIndex(todo => todo.id === action.toDo.id) const newState = update(state, {[todoIndex]: {$set: action.todDo }})
2)在上面的(1)中找到想要的待办事项的索引,然后使用$ splice方法。
const todoIndex = state.findIndex(todo => todo.id === action.toDo.id) const newState = update(state, {$splice: [[todoIndex,1,action.todDo]]})