簡體   English   中英

nextjs - 購物車總金額准確的購物車問題

[英]nextjs - shopping cart problem with accurate cart total amount

我正在建造一個購物車,但購物車總金額有困難。 當我 go 到購物車頁面總金額時,僅顯示添加到購物車的最后一項的金額。

state = {
    cart: { items: [], total: 0 },
  };

addItem = (item) => {
    let { items } = this.state.cart;
    //check for item already in cart, if not found, increase quantity by 1
    const itemFound = items.find((i) => i.id === item.id);
    if (!itemFound) {
      item.quantity = 1;
      // console.log(this.state.cart.total, item.price);
      this.setState(
        {
          cart: {
            items: [...items, item],
            total: this.state.cart.total + item.price,
          },
        },
        () => Cookie.set("cart", this.state.cart.items)
      );
    } else {
      this.setState(
        {
          cart: {
            items: this.state.cart.items.map((item) =>
              item.id === itemFound.id
                ? Object.assign({}, item, { quantity: item.quantity + 1 })
                : item
            ),
            total: this.state.cart.total + item.price,
          },
        },
        () => Cookie.set("cart", this.state.cart.items)
      );
    }
  };

更新我發現當我手動導航到購物車頁面時會出現問題,例如:http://localhost:3000/cart

如果我通過“下一個鏈接”導航到購物車頁面,它會顯示正確的總數,但是在頁面刷新時,它會再次顯示添加到購物車的最后一件商品的數量作為總金額
下面是我如何檢索購物車和設置 state

componentDidMount() {
    const cart = Cookie.get("cart");
    //if items in cart, set items and total from cookie
    if (typeof cart === "string" && cart !== "undefined") {
      JSON.parse(cart).forEach((item) => {
        this.setState({
          cart: { items: JSON.parse(cart), total: item.price * item.quantity },
        });
      });
    }
  }

我目前將購物車項目存儲在 cookie 中,而不是全部
這種方法有問題,我無法弄清楚。 期待指導 謝謝

在設置 state 之前,您需要將項目的數量乘以該項目的相應價格以獲得總價格。

例子:

let total = this.state.cart.items.reduce(
      (accumalatedQuantity, cartItem) =>
         accumalatedQuantity + cartItem.quantity * cartItem.price,
      0
   )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM