简体   繁体   中英

Deleting Items from my ReactJs Shopping Cart Object

So I'm making a shopping cart, and I want to be able to delete things from my cart. I can add the values without any problem, but they won't delete for some reason. Here is my code:

   function addToCart(e) {
  var updatedCart = { ...cart };
  if (!updatedCart[e.target.textContent]) {
    updatedCart[e.target.textContent] = 1;
  } else {
    updatedCart[e.target.textContent] += 1;
  }
  setCart(updatedCart);
}
function removeItem(item) {
  var cartCopy = {...cart}
  delete cartCopy[item]
  setCart(cartCopy)
}

Any idea? Thanks in advance.

  function removeItem(item) {
   const cardCopy = Object.entries(cart).reduce((acc, [key, value]) => {
     return key !== item ? {...acc, [key]: value} : acc;
   }, {})
   setCart(cardCopy)
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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