【问题标题】:Get initial value of Firestore document获取 Firestore 文档的初始值
【发布时间】:2022-01-16 05:43:04
【问题描述】:

我正在尝试在我的 react native 应用中添加杂货数量。杂货来自具有预定义价格的firebase firestore,我希望当我增加数量时,应该正确计算cart_items 的总数。我正在通过直接从服务器添加它来解决这个问题。

问题是,我只需要能够获得杂货店的初始价格,所以我可以随意加减,相反,当我添加数量时,我会得到更新的价格,更新的价格是当我需要再次增加数量时被添加到当前价格中。我希望你明白我的意思。

const increment = async (id) => {
    const itemRef = doc(db, "cartItems", id);
    await getDoc(itemRef).then(async (snapshot) => {
      // This Line of code is supposed to capture the initial value of the price
      let price = snapshot.data().data.price;
      console.log(price);
      // This Line of code is supposed to capture the initial value of the price
      await updateDoc(itemRef, {
        quantity: snapshot.data().quantity + 1,
        data: {
          ...snapshot.data().data,
          price: snapshot.data().data.price + price,
          // I am supposed to use that initial value for this calculation
        },
      });
    });
  };

这是为了减少数量

const decrement = async (id) => {
const itemRef = doc(db, "cartItems", id);
await getDoc(itemRef).then(async (snapshot) => {
  // This Line of code is supposed to capture the initial value of the price
  let price = snapshot.data().data.price;
  console.log(price);
  // This Line of code is supposed to capture the initial value of the price
  await updateDoc(itemRef, {
    quantity:
      snapshot.data().quantity === 1 ? 1 : snapshot.data().quantity - 1,
    data: {
      ...snapshot.data().data,
      price:
        snapshot.data().data.price === price
          ? price
          : snapshot.data().data.price - price,
          // I am supposed to use that initial value for this calculation
    },
  });
});

};

所以我只需要知道是否有一种方法可以只获取价格的初始值而不是更新后的值。如果我需要澄清有关该问题的任何内容,请告诉我。这对我来说是一个非常紧迫的问题。

【问题讨论】:

    标签: javascript reactjs firebase react-native google-cloud-firestore


    【解决方案1】:

    我得到了答案,伙计们。

    我只需要添加一个保持不变且不会更改到我的数据库的初始值。这就是我用来对我的应用进行必要计算的方法。

    【讨论】:

    • 您是否需要将购物车产品信息与服务器同步的业务逻辑?读取和写入数据库是一个异步操作,根据用户设备的网络速度应该需要几毫秒或几秒。为什么你不在前端级别做这些操作?
    • 是的,我明白你的意思。我没有在“前端级别”这样做的原因是因为所有操作都需要直接来自这个特定应用程序的数据库。如果是另一种情况,我通常会处理前端的逻辑。
    猜你喜欢
    • 1970-01-01
    • 2020-07-05
    • 2021-07-20
    • 2018-09-03
    • 2019-09-29
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2020-11-20
    相关资源
    最近更新 更多