[英]Getting a total price of cart products
I am working on a project here and I ran into a little issue.我正在这里做一个项目,但遇到了一个小问题。 Now I need to get the price of all items in the cart and add it together to make a "total: {price}", and well.现在我需要获取购物车中所有商品的价格并将其加在一起以形成“总计:{price}”,然后就可以了。 My brain is just completely still at the moment.我的大脑此刻完全静止。
Now here is the code I am using:现在这是我正在使用的代码:
const { cartItems } = useContext(AddToCartContext);
const [totPrice, setTotPrice] = useState(0);
let cart = cartItems.filter(
(ele, ind) => ind === cartItems.findIndex((elem) => elem.id === ele.id)
);
useEffect(() => {
cart.forEach((item) => {
setTotPrice(totPrice + item.price);
console.log(item.price);
});
}, []);
console.log(`${totPrice}`);
I am very aware that this does not work, as the totPrice
useState is resetting itself to 0, as its the initial value.我非常清楚这不起作用,因为totPrice
useState 将自身重置为 0,作为其初始值。 But I am not really sure how I can tackle this?但我不确定如何解决这个问题?
I need it to take all products, which could perhaps be 10 products.我需要它来获取所有产品,可能是 10 种产品。 And then add the price of all those 10 products, to get a total.然后将所有这 10 种产品的价格相加,得到总和。
Any ideas can help!任何想法都可以提供帮助!
you don't need an additional state here.您在这里不需要额外的 state。 All you need is an derived value from the state.您所需要的只是来自 state 的派生值。
const { cartItems } = useContext(AddToCartContext);
let cart = cartItems.filter(
(ele, ind) => ind === cartItems.findIndex((elem) => elem.id === ele.id)
);
const totalPrice = cart.reduce(
(totalPrice, item) => totalPrice + item.price,
0
);
Use Array.prototype.reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce使用 Array.prototype.reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
let totalPrice = cartItems.reduce((total, cartItem) => total + cartItem.price);
setTotPrice(totalPrice);
Ah another answer beat me to it.啊,另一个答案打败了我。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.