【问题标题】:array.findIndex is not a functionarray.findIndex 不是函数
【发布时间】:2020-03-16 09:48:31
【问题描述】:

在 react native 中构建购物车时,当购物车为空时,我可以在购物车中添加商品,但是如果我离开屏幕然后再次返回以添加更多商品或增加购物车中现有商品的数量,我会得到一个错误“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
}]

【问题讨论】:

  • Promise 解析时数据的值是多少:.then(data => { console.log(data); setCartItems(data); })
  • @Dan an array... [{"_id":"5e6aacca73fa9c323d666462","name":"黑色T恤","description":"A级面料。很棒的黑色T恤","price":10.99,"image":{"url":"/uploads/069963b003e5457ebee681a6537dbedc.png","__typename":"UploadFile"},"__typename":"Product","quantity":1}]

标签: javascript react-native shopping-cart


【解决方案1】:

你应该把字符串解析成json对象

cartItems  = JSON.parse(cartItems);

【讨论】:

  • 谢谢,当我从 asyncstorage 获取项目时解析时出错,现在我尝试在 .then 中解析它,它可以工作,谢谢
猜你喜欢
  • 2021-11-13
  • 2020-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-06
  • 2019-12-20
  • 1970-01-01
相关资源
最近更新 更多