首页 > 解决方案 > 不正确的数组索引正在删除 react/redux

问题描述

我正在 react/redux 应用程序中构建购物车,但无法从我的数组中删除该项目。

这是我现在拥有的代码。

case REMOVE_ITEM:
    const cloned_array = state.items.slice()

    cloned_array.splice(action.payload, 1)

    return { ...state, items: cloned_array }

我正在尝试在我的州内克隆 items 数组。然后将该数组与发送到我的action.payload中的reducer的索引拼接起来。然后返回状态,并将 items 数组设置为 clonedArray。

这导致我的 items 数组中的第一个项目被删除,而不是位于发送到 reducer 的索引中的项目。

标签: reactjsredux

解决方案


您可以通过一种方法使用.filter(). 它实现了相同的目标,.slice但现在您不需要将切片输出保存在单独的数组中。

case REMOVE_ITEM:
   return {
    ...state,
    items: state.items.filter((item, index, array) => {
       return index !== action.payload
    })
   }

推荐阅读