Javascript array.findIndex不是函数
在react native中构建购物车时,当购物车为空时,我可以在购物车中添加项目,但如果我离开屏幕,然后再次回来添加更多项目或增加购物车中现有项目的数量,我会收到一个错误“cartItems.findIndex不是一个函数” 这是密码Javascript array.findIndex不是函数,javascript,react-native,shopping-cart,Javascript,React Native,Shopping Cart,在react native中构建购物车时,当购物车为空时,我可以在购物车中添加项目,但如果我离开屏幕,然后再次回来添加更多项目或增加购物车中现有项目的数量,我会收到一个错误“cartItems.findIndex不是一个函数” 这是密码 const [cartItems, setCartItems] = useState([]); const setCart = async value => { if (AsyncStorage) { await AsyncStorage.s
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)中获得的数据
您应该将字符串解析为json对象
cartItems = JSON.parse(cartItems);
当承诺解析时,数据的值是什么:
.then(data=>{console.log(data);setCartItems(data);})
@danan数组。。。[{“_id”:“5E6AACCA73FA9C323D66462”,“名称”:“黑色T恤”,“描述”:“A级面料.令人敬畏的黑色T恤”,“价格”:10.99,“图像”:“{”url:“/uploads/069963b003e5457ebee681a6537dbedc.png”,“_u类型名”:“UploadFile”},“uu类型名”:“产品”,“数量”:1}]谢谢,当我从异步存储中获取项目时,出现错误,现在我试着把它解析进去。然后它就工作了,谢谢
cartItems = JSON.parse(cartItems);