如何删除多个数组项并设置状态?我从复选框中选择了多个项目。这是选中的项目[5、4、3]我想基于id删除数组中的所有项目并更新状态。这是我的代码。
const [products, setProducts] = useState();
const DeleteProducts = () => {
const selectedItems = [5, 4, 3];
selectedItems.forEach(function(p) {
setProducts(products.filter(prd => prd.id !== p));
});
}
它一次只删除一项,但是我选择了3项。如何删除3个选定项目和产品状态? 谢谢
答案 0 :(得分:0)
您要在循环的每次迭代中调用setProducts。过滤它们后必须调用setProducts,以便它仅触发一次状态更改
const [products, setProducts] = useState();
const DeleteProducts = () => {
const selectedItems = [5, 4, 3];
let newProducts;
selectedItems.forEach(function(p) {
newProducts = products.filter(prd => prd.id !== p);
});
setProducts(newProducts);
}
更好的是,您可以像这样更快地过滤它而无需循环
const DeleteProducts = () => {
const selectedItems = [5, 4, 3];
const newProducts = products.filter(prd => selectedItems.indexOf(prd.id) >= 0);
setProducts(newProducts);
}