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

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

问题描述

我知道我不应该改变输入,而应该克隆对象来改变它.我遵循 redux starter 项目中使用的约定:

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

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

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

用于删除我使用的:

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.

即使您返回了一个新对象,您仍然在污染旧对象,这是您永远不想做的.这使得在旧状态和新状态之间进行比较时会出现问题.例如在 shouldComponentUpdate 中,react-redux 在幕后使用.它还使时间旅行变得不可能(即撤消和重做).

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).

相反,使用不可变的方法.始终使用 Array#slice,不要使用 Array#splice.

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

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

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天全站免登陆