从 firestore 读取数据的正确方法,以避免重复数据渲染

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

我一直在构建一个基于 React 的电子商务平台作为个人投资组合项目,使用 firebase 作为后端服务。到目前为止,我已经设置好它,用户可以创建一个帐户并使用 firebase auth 登录。我正在建立一个添加到购物车的功能,点击“添加到购物车”按钮,它将数据发送到我创建的 firestore 数据库。到目前为止,我能够接收数据库中的所有数据,但是当我去阅读它时,它会以重复的形式呈现到我的页面。因此,尽管数据库中只有一项,但其中两项会呈现到我的页面。我已经查看了文档,但由于我对这项服务还很陌生,所以我很难在其中找到相关信息。

在这里找到类似的东西后,我尝试添加一个退订方法,但它似乎只是偶尔起作用。我会将一个项目添加到购物车,然后当我重新加载页面时它仍然会重复,但如果我返回产品页面并添加另一个项目它会重新呈现不重复。查看控制台,我仍然可以看到产品阵列正在重复,但我只能让它偶尔触发非重复版本,这对我来说很奇怪。在做了一天的大量阅读之后,我最接近的猜测是快照方法和它在我的浏览器中缓存的方式发生了一些事情,但我在取得任何有益的进展时遇到了麻烦。这是我用来从 firestore 数据库获取数据的方法:

useEffect(() => {
    const auth = getAuth();
    const user = auth.currentUser;
    const userId = user ? user.uid : null;

    // Construct a query to retrieve all cart items for the current user
    const cartItemsRef = collection(db, "cartItems");
    const q = query(cartItemsRef,  where("userId", "==", userId));
    
    const unsubscribe = onSnapshot(q, (snapshot) => {
        snapshot.docChanges().forEach((change) => {
          
          if (change.type === "added") {
              console.log("New product: ", change.doc.data());
          }
          if (change.type === "modified") {
              console.log("Modified product: ", change.doc.data());
          }
          if (change.type === "removed") {
              console.log("Removed product: ", change.doc.data());
          }
        });
      });

    // Retrieve the cart items and log them to the console
    getDocs(q)
        .then((getDocs) => {
        
        getDocs.forEach((doc) => {
            addItemToCart.push(doc.data());
        });
        // I was using this to log the data to see how it was returning
        getDocs.forEach((doc) => {
            console.log(doc.id, " => ", doc.data());
          });
        setCartItems(addItemToCart)
        })
        .catch((error) => {
        console.log("Error getting documents: ", error);
        });
}, [])

任何帮助将不胜感激。谢谢大家

reactjs firebase google-cloud-firestore react-hooks shopping-cart
© www.soinside.com 2019 - 2024. All rights reserved.