【问题标题】:cannot increment item in cart无法增加购物车中的商品
【发布时间】:2021-12-26 14:57:56
【问题描述】:

每当我将商品添加到购物车时,我都想增加商品数量。我的代码不起作用,我在 Cart.js 中收到错误“无法读取未定义的属性(读取'长度')”,我不知道为什么。谁能帮我?非常感谢!

代码沙盒链接:https://codesandbox.io/s/redux-shop-cart-forked-tlpek?file=/src/components/Cart.js

【问题讨论】:

  • 原因是您没有在 app.js 中将“cartItems”作为道具传递。为了解决这个问题,您需要将空值传递给 app.js 中的“cartItems”道具,或者在 Cart.js 中定义默认道具
  • 您正在将项目添加到新变量“cartItems”,但不会更新状态。

标签: reactjs increment


【解决方案1】:

您忘记从父 (app.js) 组件传递 cartItems 属性。

...
// in line no:75
 <Cart cartItems={this.state.cartItems} />
...

同时更改您的 addToCart 方法:

// in line no: 19
addToCart = (product) => {
    const isInCart = cartItems.some((item) => item.id === product.id);
    let newCart = [];
    if (isInCart) {
      newCart = this.state.cartItems.map((cart) => {
        return {
          ...cart,
          quantity: Number(cart.quantity) + 1
        };
      });
    } else {
      newCart = [...this.state.cartItems, { ...product, quantity: 1 }];
    }
    this.setState({
      cartItems: newCart
    });
  };

您在 cart.js 文件中期待 cartItems 属性,但您没有从父组件传递它。

【讨论】:

  • 我修复了它,它可以工作,但是当我点击添加到购物车按钮时,我的购物车中的数量不会增加。你能帮助我吗?更新链接:codesandbox.io/s/redux-shop-cart-forked-tlpek?file=/src/App.js
  • 我已经添加了addToCart 方法,如果您需要任何信息,请告诉我。如果我已经回答了你的问题,请接受。谢谢!
  • 谢谢,它可以工作,但无论我点击 2 个或更多项目,数量都保持为 1...
【解决方案2】:

这是因为在 APP.js 中,在第 75 行调用 &lt;Cart /&gt; 时,您没有传递道具,而是尝试从 card.js 中 4 const { cartItems } = props; 处的道具访问值,因此它将是未定义的和长度无法在 undefined 上读取。

我建议将 app.js 中的第 75 行更改为 &lt;Cart cartItems={this.state.cartItems}/&gt;

更正:

addToCart = (product) => {
let alreadyIncart = false;
let cartItems = this.state.cartItems.slice();
cartItems.length !== 0
  ? cartItems.forEach((item) => {
      if (item.id === product.id) {
        item++;
        alreadyIncart = true;
      }
      if (!alreadyIncart) {
        cartItems.push({ ...product, count: 1 });
      }
    })
  : cartItems.push({ ...product, count: 1 });
this.setState({ cartItems: cartItems });
};

【讨论】:

  • 我修复了它,它可以工作,但是当我点击添加到购物车按钮时,我的购物车中的数量不会增加。你能帮助我吗?更新链接:codesandbox.io/s/redux-shop-cart-forked-tlpek?file=/src/App.js
  • 这是因为您没有更新状态而是更新了您创建的局部变量,我可以更正吗?
  • 你能在我的答案中引用更正的部分并在你的代码中替换它,它会起作用吗?
  • 我将不胜感激接受或支持
  • 谢谢,它可以工作,但无论我点击 2 个或更多项目,数量都保持为 1...
猜你喜欢
  • 2015-03-28
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-01
  • 2018-02-22
  • 2017-11-21
相关资源
最近更新 更多