【发布时间】:2019-02-13 07:36:46
【问题描述】:
我在解析本地存储中的对象数组的函数时遇到了一个奇怪的错误。
尝试:从本地存储中获取对象并将其productID 和selectedQty 属性值解析为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