【发布时间】:2022-01-23 09:19:43
【问题描述】:
我需要能够通过单击购物车元素上的按钮来删除我以数组状态(挂钩)存储的产品。但是每次我点击我的按钮时,它都会删除存储在数组中的全部项目。
这是我的代码:
export const CartContext = createContext([]);
export function CartProvider({ children }) {
const [products, setProducts] = useState([]);
const [total, setTotal] = useState(0);
//Adding items.
const addItem = (product, quantity, id) => {
if(quantity === 1){
alert("Product added to carrr")
} else {
alert("Products added to cart")
};
setProducts([...products, {...product, quantity : quantity, id:id}]);
console.log("Producto: ", product);
setTotal(products.length + 1)
};
// const totalCart = ({products, quantity}) =>{
// setTotal (products.map(product => product.price).reduce((prev, next)=> prev + next)*quantity);
// console.log ("El totalCart: ", total);
// }
//Avoiding duplicates
const isInCart = (id) => {
const existe = products.find((e) => e.id === id);
console.log("Existe", existe)
return existe;
};
//Clearing the cart
const clearCart=()=>{
setProducts([]);
console.log("Carro vacío");
alert("El carro está vacío")
setTotal(0);
}
//Removing items one by one
const removeItem = (id) => {
const deleted = products.filter((product) => product.id !== id);
setProducts(deleted);
setTotal(products.length - 1);
alert("Se quitó un producto")
};
return (
<CartContext.Provider value={{ products, addItem, total, clearCart, isInCart, removeItem }}>
{children}
</CartContext.Provider>
);
}
然后我将上下文发送到购物车,顺便提醒我,我应该为列表中的每个项目都有一个键,但似乎没有注意到我正在尝试定义键
const Cart = () =>{
const { products, total, clearCart, removeItem} = useContext(CartContext);
console.log("Products in cart: ", products);
console.log ("Total of items: ", total );
return(
<div>
<h1>Productos en el carro: {products.length}</h1>
<div>
{products.map((product) => {
return (
<Fragment >
<div key={product.id}>
<p>cantidad agregada: {product.quantity}</p>
<button onClick={()=>removeItem(product.id)}>Quitar</button>
</div>
</Fragment>
);
})}
</div>
<button onClick={clearCart}>Limpiar carro</button>
</div>
)
}
导出默认购物车
【问题讨论】:
-
在上下文提供程序中使用状态挂钩有点困惑。 “这就是为什么状态通常被称为本地或封装的原因。除了拥有和设置它的组件之外,任何组件都无法访问它。” - reactjs.org/docs/state-and-lifecycle.html 我建议尝试使用 useReducer hook 来完成你的工作
标签: arrays reactjs react-hooks