简体   繁体   English

React hooks - 从数组中删除多对象并更新状态

[英]React hooks - Remove multi object from array and update state

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我从复选框中选择了多个项目 这是选定的项目 [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));
    });
}

Its removing only one item at time, but I selected 3 items.它一次只删除一项,但我选择了 3 项。 How to show remaining items except 3 selected items in products state?如何在产品状态中显示除 3 个选定项目之外的剩余项目? Thanks谢谢

You can simplify it to a single filter function:您可以将其简化为单个过滤器功能:

const DeleteProducts = () => {
  setProducts(prevProducts => {
    return prevProducts.filter(p => ! p.selected);
  });
}
const DeleteProducts = () => {
  const filteredProducts = products.filter(product => !product.selected);
  setProducts(filteredProducts);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM