【发布时间】:2025-12-25 02:35:06
【问题描述】:
我有一个如下所示的删除函数:
this.deleteItem = item => event => {
const { res, selectedItems } = this.state;
res.splice(res.indexOf(item), 1);
selectedItems.splice(res.indexOf(item), 1);
this.setState({
res
});
};
这里,res 是页面上显示的项目列表,selectedItems 是选择了哪些项目的列表。当 res 中的一个项目被删除时,selectedItems 应该被更新以从列表中删除该项目的索引。
但是,每当我尝试删除特定项目时,它只会删除添加到数组中的最后一个项目,而不是与单击的目标索引对应的项目。它的索引方式肯定有问题,但我一直无法确定来源。
我也尝试过引用here,但这不起作用,因为我需要将item 作为参数。
有什么好的方法可以解决这个问题?
非常感谢。
编辑:将函数更改为看起来像 @HMK 的响应。删除一个项目后,render 方法中console.log(res) 的输出是一个对象数组,其形式如下:
res
(9) […]
0: Object { id: 0, name: "a", description: "description of a", … }
1: Object { id: 2, name: "b", description: "description of b", … }
2: Object { id: 3, name: "c", description: "description of c", … }
3: Object { id: 4, name: "d", description: "description of d", … }
4: Object { id: 5, name: "e", description: "description of e", … }
5: Object { id: 6, name: "f", description: "description of f", … }
6: Object { id: 7, name: "g", description: "description of g", … }
7: Object { id: 8, name: "h", description: "description of h", … }
8: Object { id: 9, name: "i", description: "description of i", … }
length: 9
<prototype>: Array []
deleteItem函数中console.log(JSON.stringify(item,undefined,2));的输出是从数组中删除的对象。
例如:
{
"id": 10,
"name": "j",
"description": "description of j",
"icon": "jIcon",
"selected": false
}
当页面上的所有项目都被选中时,console.log("selecteditems:", JSON.stringify(selectedItems))的输出:
selecteditems: [0,1,2,3,4,5,6,7,8,9,10]
【问题讨论】:
-
不要改变使用Array.prototype.filter 来创建一个删除项目的新数组。如果你这样做并且组件仍然呈现,那只意味着你没有优化任何东西(纯组件或 useMemo)
标签: javascript arrays reactjs indexing state