【问题标题】:Getting a total price of cart products获取购物车产品的总价
【发布时间】:2021-05-23 19:13:25
【问题描述】:

我正在这里做一个项目,但遇到了一个小问题。现在我需要获取购物车中所有商品的价格并将其相加以形成“总计:{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 种产品的价格相加,得到总和。

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

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    这里不需要额外的状态。您所需要的只是从状态中导出的值。

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

    【讨论】:

    • 啊!谢谢,这么简单的事也哈哈。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 2013-11-01
      • 2017-04-27
      • 2019-12-09
      • 2020-03-05
      • 2017-08-07
      相关资源
      最近更新 更多