【问题标题】:how to update redux state using immutability helper?如何使用不变性助手更新 redux 状态?
【发布时间】:2018-10-31 03:41:11
【问题描述】:

我正在尝试更新我的 redux crud 表单。我在 immutatbility helper 的帮助下使用。 我的减速机是:

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", …}
]

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    您的代码不是针对您要在状态中更新的特定待办事项,因此它会替换整个状态。有两种方法可以实现:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多