【发布时间】:2020-09-08 00:07:58
【问题描述】:
我初始化对象和数组的方式有问题吗? 我正在尝试将购物车数据保存到 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);
}
};
【问题讨论】:
-
cartIteminlocalStorage是一个字符串。所以你需要先deserialize它和JSON.parse,然后再将项目添加到数组中
标签: javascript reactjs