array.findIndex不是函数

问题描述 投票:0回答:1

虽然在本机中构建购物车时,当购物车为空时,我可以在购物车中添加商品,但是如果我离开屏幕然后再次返回以添加更多商品或增加购物车中现有商品的数量,则会收到错误消息“ 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
}]
javascript react-native shopping-cart
1个回答
0
投票

您应该将字符串解析为json对象

cartItems  = JSON.parse(cartItems);
© www.soinside.com 2019 - 2024. All rights reserved.