React Native 购物车使用 AsyncStorage 跟踪 COUNT

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

我正在创建一个购物应用程序,但我的购物车有问题。每次我设法增加一件物品的数量时,我最终都会增加每一件物品的数量。

代码如下

从另一个文件中获取数据的函数

const MyCart = ({ navigation }) => {

  const [product, setProduct] = useState();
  const [total, setTotal] = useState(null);
  const [count, setCount] = useState(null);

  useEffect(() => {
    const unsubscribe = navigation.addListener("focus", () => {
      getDataFromDB();
    });
    return unsubscribe;
  }, [navigation]);

  //get data from local DB by ID
  const getDataFromDB = async () => {
    let items = await AsyncStorage.getItem("cartItems");
    let count = await AsyncStorage.getItem("@count");
    count = parseInt(count);
    items = JSON.parse(items);
    let productData = [];
    let countID = [];
    if (items) {
      Items.forEach((data) => {
        if (items.includes(data.id)) {
          productData.push(data);
          countID.push(data.count);
          return;
        }
      });
      setProduct(productData);
      getTotal(productData);
      getCount(countID);
      setCount(isNaN(count) ? 0 : count);
    } else {
      setProduct(false);
      getTotal(false);
      getCount(false);
    }
  };

递增和递减

const increment = async (id) => {
    let itemArray = await AsyncStorage.getItem("cartItems");
    itemArray = JSON.parse(itemArray);
    for (let i = 0; i < itemArray.length; i++) {
      if (itemArray[i] == id) {
        itemArray[i].count++;
        await AsyncStorage.setItem("@count", (count + 1).toString());
        setCount(itemArray[i].count);
        break;
      }
    }
  };



  const decrement = async (id) => {
    let itemArray = await AsyncStorage.getItem("cartItems");
    itemArray = JSON.parse(itemArray);
    for (let i = 0; i < itemArray.length; i++) {
      if (itemArray[i] == id) {
        await AsyncStorage.setItem("@count", (count - 1).toString());
        setCount(count - 1);
      }
    }
  };

我也像这样构建了我的 Database.js 文件

export const Items = [
  {
    id: 1,
    category: "featured",
    count: 0,
    productName: "1800",
    productPrice: 17.99,
    description: "Tequila",
    isOff: true,
    offPercentage: "10%",
    isAvailable: true,
    productImage: require("../database/images/1800.png"),
    productImageList: [
      require("../database/images/1800.png"),
      require("../database/images/1800-reposado.webp"),
    ],
  },

由于某种原因,我的所有物品的数量都增加了。我已经5天熬夜试图解决这个问题了,请帮忙!

前端完全没问题,由于某种原因我只是无法增加特定 ID 的计数

react-native expo asyncstorage
1个回答
0
投票

我在这些项目中有两个购物车的示例,请看一下。这可以帮助您修复它。

https://github.com/rodrigodiasf1984/test-cart-next.js-tailwind https://github.com/rodrigodiasf1984/OnlineShop/tree/master/frontend

© www.soinside.com 2019 - 2024. All rights reserved.