【问题标题】:Remove item from redux array by index按索引从 redux 数组中删除项目
【发布时间】:2018-04-02 19:17:05
【问题描述】:

我有一个数组存储在我的 react redux 存储中。这些项目由title 组成,仅此而已(没有id 字段本身)。

当我触发一个动作时,我尝试通过减速器更新我的商店

case REMOVE_NOTIFICATION: 
    return {
        ...state,
        notifications: state.notifications.filter(id => action.id !== id)
    }

action.id 是正确的,但调用它似乎没有任何作用。我希望它会返回一个新的项目数组,其中 action.id 与传入的项目的 id 不匹配。假设id 实际上是数组项目的索引,我是否正确?

【问题讨论】:

  • 假设 id 实际上是数组项的索引是否正确?不,id 不会是项目索引,如果你想使用索引,那么这样写:state.notifications.filter((id, index) => action.id !== index)

标签: arrays reactjs redux


【解决方案1】:

No 在过滤器函数中,第一个参数总是值,第二个参数是索引/键

试试这个:)

case REMOVE_NOTIFICATION: 
    return {
        ...state,
        notifications: state.notifications.filter((obj,index) => {return action.id !== index})
    }

【讨论】:

    【解决方案2】:

    我是否正确假设 id 实际上是数组项的索引?

    没有。根据MDN Reference,您的 id 参数将是数组项(内容),而不是它们的索引。

    您可以通过过滤器函数的第二个参数访问项目的索引:

    case REMOVE_NOTIFICATION: 
    return {
        ...state,
        notifications: state.notifications.filter((item, index) => action.id !== index)
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 2019-02-15
      • 2021-11-27
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      • 2018-05-07
      相关资源
      最近更新 更多