[英]How to remove an equal item from the cart without deleting an equal?
I made e-commerce with a cart for activity using context API, but, when I am going to remove an item from the cart and I have two of them but when I remove one, I remove the other one.我使用上下文 API 使用购物车进行电子商务活动,但是,当我要从购物车中删除一件商品时,我有两个,但是当我删除一个时,我删除了另一个。 How to avoid it?如何避免?
Inside my providers, this is my catalogue:在我的提供者中,这是我的目录:
import { createContext, useState } from "react"
export const CatalogueContext = createContext([])
export const CatalogueProvider = ({ children }) => {
const [catalogue, setCatalogue] = useState([
{id: 1, name: "Affogato", price: 10, img: affogato,},
{id: 2, name: "Café preto", price: 10, img: black,},
{id: 3, name: "Capuccino", price: 10, img: cappuccino,},
{id: 4, name: "Dalgona", price: 10, img: dalgona,},
{id: 5, name: "Doppio", price: 10, img: doppio,},
{id: 6, name: "Expresso", price: 10, img: expresso,},
{id: 7, name: "Galão", price: 10, img: galao,},
{id: 8, name: "Irlandês", price: 10, img: irish},
{id: 9, name: "Latte", price: 10, img: latte,},
{id: 10, name: "Mocha", price: 10, img: mocha,}
])
return (
<CatalogueContext.Provider value={{ catalogue }} >
{children}
</CatalogueContext.Provider>
)
}
This is my cart:这是我的推车:
import { createContext, useState } from "react";
export const CartContext = createContext([])
export const CartProvider = ({ children }) => {
const [cart, setCart] = useState([])
const addToCart = (item) => {
setCart([...cart, item])
}
const removeFromCart = (item) => {
const newCart = cart.filter((itemOnCart) => itemOnCart.id !== item.id)
setCart(newCart)
}
return (
<CartContext.Provider value={{ cart, addToCart, removeFromCart}} >
{children}
</CartContext.Provider>
)
}
Can you try to use property for store a count of items in cart.您可以尝试使用属性来存储购物车中的物品数量吗? For example: When user add first item you add it in array When user try to add the same item, you need to update count for 1例如:当用户添加第一个项目时,您将其添加到数组中当用户尝试添加相同的项目时,您需要将计数更新为 1
Method map
will help you方法map
将为您提供帮助
Same logic for removing.删除的逻辑相同。 When user removes any item, you will find it in array and decrement counter.当用户删除任何项目时,您会在数组和递减计数器中找到它。 When counter will equal 0 - remove it from array当计数器等于 0 - 从数组中删除它
Method find
will help you with whis方法find
将帮助您解决问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.