REACT: TypeError: Cannot read property 'productID' of undefined

REACT: TypeError: Cannot read property 'productID' of undefined

我在解析本地存储中的对象数组的函数时遇到异常错误。

尝试: 从本地存储中获取对象并将它们的 productIDselectedQty 属性 值解析为 int.

当我记录他们的 typeof 值时,即

   console.log("parse value", typeof item.selectedQty);

我明白了 *"parse value number"...太棒了!

但是我仍然收到 REACT 错误:

TypeError: Cannot read property 'productID' of undefined

 46 | if (allItems && Array.isArray(allItems)) {
  47 |   for (let i = 0; i <= allItems.length; i++) {
  48 |     var item = allItems[i];
> 49 |     item.productID = parseInt(item.productID);
  50 | ^   item.selectedQty = parseInt(item.selectedQty);
  51 | 
  52 |     console.log("parse value", typeof item.productID);

Stack Track up to

Cart.componentDidMount
src/components/cart.jsx:14
  11 | };
  12 | componentDidMount() {
  13 |   // 1. Add Items In Cart
> 14 |   var updateCartItems = this.addItemToCart();
     | ^  15 | 
  16 |   // 2. Caclulate total cart value
  17 |   var newCartValue = this.getCartValue(updateCartItems);

code

  addItemToCart() {
    var allItems = JSON.parse(localStorage.getItem("itemsArray"));
    // console.log("--->", Array.isArray(allItems), allItems);
    // allItems.map(item => JSON.parse(item));

    var updateCartItems = this.state.cartItems;

    if (allItems && Array.isArray(allItems)) {
      for (let i = 0; i <= allItems.length; i++) {
        var item = allItems[i];
        item.productID = parseInt(item.productID);
        item.selectedQty = parseInt(item.selectedQty);

        console.log("parse value", typeof item.productID);
        console.log("parse value", typeof item.selectedQty);
        updateCartItems.push(item);
      }
    }
    return updateCartItems;
  }

  componentDidMount() {
    // 1. Add Items In Cart
    var updateCartItems = this.addItemToCart();

    // 2. Caclulate total cart value
    var newCartValue = this.getCartValue(updateCartItems);

    this.setState({ cartValue: newCartValue, cartItems: updateCartItems });
  }

我认为你的 for 循环代码有问题如果循环从 0 开始然后需要一直到 长度 - 1.

改变

for (let i = 0; i <= allItems.length; i++)

for (let i = 0; i < allItems.length; i++)