虽然在本机中构建购物车时,当购物车为空时,我可以在购物车中添加项目,但是如果我离开屏幕,然后再次返回以添加更多项目或增加购物车中现有项目的数量,则会得到错误“ cartItems.findIndex不是函数”
这是代码
const [cartItems, setCartItems] = useState([]);
const setCart = async value => {
if (AsyncStorage) {
await AsyncStorage.setItem("cart", JSON.stringify(value));
}
};
const getCart = async () => {
if (AsyncStorage && await AsyncStorage.getItem("cart")) {
return await AsyncStorage.getItem("cart");
}
return [];
};
// Get cart items on component mount
useEffect(() => {
getCart()
.then(data => setCartItems(data))
.catch(e => console.log(e));
}, []);
console.log(cartItems);
// Add to cart
const addToCart = product => {
const index = cartItems.findIndex(item => item._id == product._id);
// if item is not already in cart
if (index === -1) {
cartItems.push({
...product,
quantity: 1
});
const updateCart = [...cartItems];
setCartItems(updateCart);
setCart(updateCart);
} else {
// if item already in cart
cartItems[index].quantity += 1;
const updateCart = [...cartItems];
setCartItems(updateCart);
setCart(updateCart);
}
};
这是我console.log(cartItems)
时获得的数据[{
"_id":"5e6aacca73fa9c323d666462",
"name":"Black T-shirt",
"description":"Grade A fabric. Awesome black t-shirt",
"price":10.99,
"image":{
"url":"/uploads/069963b003e5457ebee681a6537dbedc.png",
"__typename":"UploadFile"
},
"__typename":"Product",
"quantity":1
}]
答案 0 :(得分:0)
您应该将字符串解析为json对象
cartItems = JSON.parse(cartItems);