React hooks - 从数组中删除多对象并更新状态 [英] React hooks - Remove multi object from array and update state
本文介绍了React hooks - 从数组中删除多对象并更新状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何删除数组的多个对象并更新状态?我从复选框中选择了多个项目这是选定的项目 [5, 4, 3]我想根据 id 删除数组中的所有项目并更新状态这是我的代码
How to delete multiple objects of array and update the state? I have selected multiple items from checkbox This is the selected item [5, 4, 3] I want to remove all items in array based on id and update the state This is my code
const [products, setProducts] = useState();
const DeleteProducts = () => {
const selectedItems = [5, 4, 3];
selectedItems.forEach(function(p) {
setProducts(products.filter(prd => prd.id !== p));
});
}
它一次只删除一项,但我选择了 3 项.如何在产品状态中显示除 3 个选定项目之外的剩余项目?谢谢
Its removing only one item at time, but I selected 3 items. How to show remaining items except 3 selected items in products state? Thanks
推荐答案
您可以将其简化为单个过滤器功能:
You can simplify it to a single filter function:
const DeleteProducts = () => {
setProducts(prevProducts => {
return prevProducts.filter(p => ! p.selected);
});
}
这篇关于React hooks - 从数组中删除多对象并更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文