代码之家  ›  专栏  ›  技术社区  ›  billy

react:typeerror:无法读取未定义的“productID”属性

  •  0
  • billy  · 技术社区  · 6 年前

    我得到了一个异常错误,函数解析本地存储中的对象数组。

    尝试: 从本地存储获取对象并分析它们 productID selectedQty 属性值到int。

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

       console.log("parse value", typeof item.selectedQty);
    
    我得到了 *"parse value number" 太棒了!

    但是我仍然会得到一个反应错误:

    < Buff行情>

    类型错误:无法读取未定义的“productID”属性

    < /块引用>
     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);
    
    < Buff行情>

    堆栈跟踪到

    < /块引用>
    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);
    
    < Buff行情>

    代码

    < /块引用>
      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 });
      }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Praveen Rao Chavan.G    6 年前

    我认为,如果循环从 0开始,则您的 for->strong>循环代码存在问题,然后需要转到 length-1->strong>。

    变更

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

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