【问题标题】:REACT: TypeError: Cannot read property 'productID' of undefined反应:TypeError:无法读取未定义的属性“productID”
【发布时间】:2019-02-13 07:36:46
【问题描述】:

我在解析本地存储中的对象数组的函数时遇到了一个奇怪的错误。

尝试:从本地存储中获取对象并将其productIDselectedQty 属性值解析为int。

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

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

我收到*"parse value number"...太棒了!

但是我仍然收到一个 REACT 错误:

TypeError:无法读取未定义的属性“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);

堆栈跟踪到

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

代码

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

【问题讨论】:

    标签: javascript reactjs error-handling local-storage undefined


    【解决方案1】:

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

    改变

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

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

    【讨论】:

      猜你喜欢
      • 2022-09-27
      • 2020-09-07
      • 2021-06-22
      • 2021-07-10
      • 2017-01-01
      • 2021-01-16
      • 2021-08-05
      • 1970-01-01
      • 2021-12-02
      相关资源
      最近更新 更多