【问题标题】:Redux reducer to remove an object from a list by nameRedux reducer 按名称从列表中删除对象
【发布时间】:2016-09-01 00:41:21
【问题描述】:

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

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

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

【问题讨论】:

  • 你在使用 ES6/ES7 吗?

标签: reactjs ecmascript-6 redux react-redux


【解决方案1】:

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

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

【讨论】:

  • 还没有遇到findIndex(),这很好用,谢谢!
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 2018-07-06
    • 2017-07-03
    • 2020-04-17
    • 1970-01-01
    • 2015-03-02
    相关资源
    最近更新 更多