[英]React Context delete item from Cart
I am doing a React JS Cart and I am having problems when I try to delete an Item from the there.我正在做一个 React JS 购物车,当我尝试从那里删除一个项目时遇到问题。 It has already a function that adds the items and also another for the total quantity and the total price.它已经有一个 function 用于添加项目以及另一个用于总数量和总价格的项目。 This is the ContextProvider:这是上下文提供者:
import { useState } from "react";
import { CartContext } from "./CartContext";
export const CartProvider = ({ children }) => {
const [list, setList] = useState([]);
const addCart = (varietalCount) => {
if (list.find((item) => item.id === varietalCount.id)) {
const newVarietal = list.map((varietal) => {
if (varietal.id === varietalCount.id) {
return { ...varietal, count: varietalCount.count + varietal.count };
}
return varietal;
});
setList(newVarietal);
} else {
setList((state) => {
return [...state, varietalCount];
});
}
};
console.log("list", list);
// const deleteProd = (varietalCount) => {
// if (list.find((item) => item.id === varietalCount.id)) {
// const deleteVarietal = list.map((varietal) => {
// if (varietal.id === varietalCount.id) {
// return { ...varietal, count: null };
// }
// return varietal;
// });
// setList(deleteVarietal);
// } else {
// setList((state) => {
// return [...state, varietalCount];
// });
// }
// };
const totalPrice = () => {
return list.reduce((prev, next) => (prev + (next.count * next.price)), 0)
};
const totalQuantity = () => {
return list.reduce((prev, next) => (prev + (next.count)), 0)
};
return(
<>
<CartContext.Provider value={{ list, addCart, totalPrice, totalQuantity }}>
{children}
</CartContext.Provider>
</>);
};
If it is necessary I can add to the post the Cart.js or the ItemDetail.js.如果有必要,我可以在帖子中添加 Cart.js 或 ItemDetail.js。 I hope someone can help me.我希望有一个人可以帮助我。 Cheers干杯
I think you can just use filter given that your state has value of an array.我认为您可以使用过滤器,因为您的 state 具有数组的值。 Something like:就像是:
const deleteProd = (varietalCount) => {
const newItems = list.filter((item) => item.id !== varietalCount.id)
setList(newItems);
};
You can check more array functions from here https://www.w3schools.com/jsref/jsref_obj_array.asp您可以从这里查看更多数组函数https://www.w3schools.com/jsref/jsref_obj_array.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.