繁体   English   中英

获取购物车产品的总价

[英]Getting a total price of cart products

我正在这里做一个项目,但遇到了一个小问题。 现在我需要获取购物车中所有商品的价格并将其加在一起以形成“总计:{price}”,然后就可以了。 我的大脑此刻完全静止。

现在这是我正在使用的代码:

  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}`);

我非常清楚这不起作用,因为totPrice useState 将自身重置为 0,作为其初始值。 但我不确定如何解决这个问题?

我需要它来获取所有产品,可能是 10 种产品。 然后将所有这 10 种产品的价格相加,得到总和。

任何想法都可以提供帮助!

您在这里不需要额外的 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
);

使用 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);

啊,另一个答案打败了我。 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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