Array.push 不是从 localstorage 检索到的数组上的函数
2020-09-08
508
我初始化对象和数组的方式是否有问题。 我试图将购物车数据保存到 localStorage 中。我从状态中获取数据,并在控制台中显示。登录后,对象似乎可以工作,但数组不行,我不明白代码出了什么问题。
未处理的拒绝 (TypeError):cartItemObjectArray.push 不是函数
编辑:但是,即使本地存储未定义,if 语句似乎也认为它不是未定义的,我也不知道如何解决它。
下面是我的构造函数
constructor(props) {
super(props);
this.state = {
comicId: null,
selectedOption: null,
comicPrice: null,
purchaseType: null,
priceCurrency: "$",
currencyVisibility: null,
issueObjectState: null,
seriesObjectState: null,
pricingObjectState: null,
};
}
下面是我的 onSubmit(),这样每当用户点击添加到购物车时,都会检索和设置状态值
onSubmit = async (event) => {
//submit function when adding item to cart
if (localStorage.getItem("cartitem") != undefined) {
//if there are items in the array then do this
console.log("It came not undefined");
let cartItemObjectArray = localStorage.getItem("cartitem");
let cartItemObject = {
comicid: this.state.comicId,
purchasetype: this.state.purchaseType,
};
console.log(cartItemObject);
cartItemObjectArray.push(cartItemObject);
localStorage.setItem("cartitem", cartItemObjectArray);
toast.success("Item Added to cart");
console.log("This is the mighty array ", cartItemObjectArray);
} else {
//if there are no items in the cart array in the local storage then initialize and do this
console.log("It came undefined");
let cartItemObjectArray = [];
let cartItemObject = {
comicid: this.state.comicId,
purchasetype: this.state.purchaseType,
};
console.log(cartItemObject);
cartItemObjectArray.push(cartItemObject);
localStorage.setItem("cartitem", cartItemObjectArray);
toast.success("Item Added to cart");
console.log("This is the mighty array ", cartItemObjectArray);
}
else if (cartItemFromLocalStorage == null) {
//if there are no items in the cart array in the local storage then initialize and do this
console.log("It came undefined");
let cartItemObjectArray = [];
let cartItemObject = {
comicid: this.state.comicId,
purchasetype: this.state.purchaseType,
};
console.log(cartItemObject);
cartItemObjectArray.push(cartItemObject);
localStorage.setItem("cartitem", JSON.stringify(cartItemObjectArray));
toast.success("Item Added to cart");
console.log("This is the mighty array ", cartItemObjectArray);
}
};
2个回答
本地存储仅支持字符串。请尝试将数组字符串化以保存它,然后在从本地存储获取它时对其进行解析。
// Save the array in local storage
localStorage.setItem("cartitem",JSON.stringify(cartItemObjectArray));
// Retrieve the array from local storage
var cartItemObjectArray = JSON.parse(localStorage.getItem("cartitem"));
Edward Romero
2020-09-08
因为 localStorage 只是用构造键值存储数据,所以在存储之前需要将数组转换为 Javascript 字符串对象。您已更改代码中的所有 setItem:
localStorage.setItem("data",JSON.stringify(cartItemObjectArray));
请记住在 UI 上显示数据之前检索 Javascript 字符串对象:
JSON.parse(localStorage.getItem("data"))
Khanh Le Tran
2020-09-08