Redux reducer用于按名称从列表中删除对象

时间:2016-05-06 03:53:22

标签: reactjs ecmascript-6 redux react-redux

我见过的关于从列表中删除项目的大多数示例都使用列表中项目的索引,例如:

case REMOVE:
  return [
    ...list.slice(0, action.index)
    ...list.slice(action.index + 1)
  ]

但是,如果我想调度一个无法访问列表中项目索引但只能访问名称的操作,我该如何过滤一组对象并仅删除一个带有{的对象{1}}名字?

2 个答案:

答案 0 :(得分:25)

更简单的方法是使用数组filter函数

case REMOVE:
  return list.filter((item) => item.name !== n)

答案 1 :(得分:6)

如果您使用ES6 +来查找索引,则可以使用findIndex()方法。

case REMOVE:
  let index = list.findIndex((x) => x.name === n); 
  return [
    ...list.slice(0, index),
    ...list.slice(index + 1)
  ]