这是使用redux删除项目的正确方法吗? [英] Is this the correct way to delete an item using redux?

查看:467
本文介绍了这是使用redux删除项目的正确方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我不应该改变输入并且应该克隆对象以使其变异。我遵循使用的redux启动项目中使用的约定:

  ADD_ITEM :( state,action)=> ({
...州,
项目:[... state.items,action.payload.value],
lastUpdated:action.payload.date
})

用于添加项目 - 我使用spread来将项目附加到数组中。



删除我使用过:

  DELETE_ITEM :(州,行动)=> ; ({
...州,
项目:[... state.items.splice(0,action.payload),... state.items.splice(1)],
lastUpdated:Date.now()
})

但这改变了输入状态对象 - 即使我要返回一个新对象,这是禁止的吗?

解决方案

没有。永远不要改变你的状态。



即使你正在返回一个新对象,你仍然会污染你永远不想做的旧对象。这使得在旧状态和新状态之间进行比较时存在问题。例如在 shouldComponentUpdate 中,react-redux会在引擎盖下使用。它也使得时间旅行变得不可能(即撤消和重做)。



相反,使用不可变方法。始终使用 Array#slice 并且永远不要 Array#splice



<我假设你的代码中 action.payload 是要删除的项目的索引。更好的方法如下:

  items:[
... state.items.slice(0, action.payload),
... state.items.slice(action.payload + 1)
],


I know I'm not supposed to mutate the input and should clone the object to mutate it. I was following the convention used on a redux starter project which used:

ADD_ITEM: (state, action) => ({
  ...state,
  items: [...state.items, action.payload.value],
  lastUpdated: action.payload.date
})

for adding an item - I get the use of spread to append the item in the array.

for deleting I used:

DELETE_ITEM: (state, action) => ({
  ...state,
  items: [...state.items.splice(0, action.payload), ...state.items.splice(1)],
  lastUpdated: Date.now() 
})

but this is mutating the input state object - is this forbidden even though I am returning a new object?

解决方案

No. Never mutate your state.

Even though you're returning a new object, you're still polluting the old object, which you never want to do. This makes it problematic when doing comparisons between the old and the new state. For instance in shouldComponentUpdate which react-redux uses under the hood. It also makes time travel impossible (i.e. undo and redo).

Instead, use immutable methods. Always use Array#slice and never Array#splice.

I assume from your code that action.payload is the index of the item being removed. A better way would be as follows:

items: [
    ...state.items.slice(0, action.payload),
    ...state.items.slice(action.payload + 1)
],

这篇关于这是使用redux删除项目的正确方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆