如何删除数组的多个项并设置状态?我已从复选框中选择了多个项目。这是所选的项目[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个选定的项目和产品状态?感谢
您在循环的每次迭代中都调用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);
}