reactjs - 不正确的数组索引正在删除 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 的索引中的项目。
解决方案
您可以通过一种方法使用.filter()
. 它实现了相同的目标,.slice
但现在您不需要将切片输出保存在单独的数组中。
case REMOVE_ITEM:
return {
...state,
items: state.items.filter((item, index, array) => {
return index !== action.payload
})
}
推荐阅读
- javascript - 如何统一 Kotlin 和 Long.js 的划分结果
- reactjs - 如何单击 h1 标题以导航到组件?
- wordpress - 无法使用 WPGQL 获取菜单数据
- arrays - MIPS - 存储整数,排列它们,然后将整数加到一个总和中
- python - Django模板过滤已经呈现的查询集
- java - 如何优化 Hibernate buildSessionFactory();
- readline - 如何使用 readline() 连接字符串
- security - 通过浏览器上传整个 CdRom
- discord.js - 从特定频道中的特定消息中删除所有反应
- c - 在 c 中的拼写程序中实现多个函数会返回所有拼写错误的单词。在 cs50 pset5 拼写器中