reactjs - Firestore get() 和 onSnapshot 函数在 useEffect 中不起作用

标签 reactjs firebase google-cloud-firestore react-hooks

我正在尝试从 Firestore 集合中获取所有文档。我正在按照他们的文档来这样做。然而,什么也没有发生。我没有看到任何控制台日志记录或任​​何错误。基本上什么也没有发生,就好像 get() 函数不起作用一样。我不知道发生了什么。

这是带有 get() 的代码。它是用 ReactJS 编写的,带有钩子(Hook):

import React, { useState, useEffect } from 'react';
import firebase from '../firebase.js';
import './Messages.css';


function Messages (props) {


    const [messages, setMessages] = useState([]);
    const [customers, setCustomers] = useState([]);   

    useEffect(() => {         
    
            const query = firebase
            .firestore()
            .collection("Chats")
            .get()
            .then((querySnapshot) => {           
                querySnapshot.forEach((doc) => {
    
                    if (doc.exists) {
                        console.log(doc)                    
                    } else {
                        console.log('nothing')
                    }
                   console.log(doc.id, " => ", doc.data());
                });
            }).catch((error) => {
                console.log("Error getting documents: ", error);
            });
    
     }, []);

同样,我尝试使用的 onSnapShot 函数也发生了同样的情况,如下所示:

    useEffect(() => {         
        
               const unsub = query.onSnapshot(async querySnapshot => {
    
                if (querySnapshot.docChanges().length > 0) {
    
                    const data = querySnapshot.docs.map((doc) => {
    
                        return { body: doc.data(), id: doc.id }
    
                    }
    
                    );
    
                    const allData = await Promise.all(data)
    
                    setCustomers(allData);
                    
    
                } else { console.log("no data") }
    
            }, (error) => {
                console.log("Error listening to documents: ", error);
            })
   return () => {
            unsub();
        };

         }, []);

客户状态为空,并且从 Querysnapshot 功能中的任何位置进行控制台日志记录都不起作用。然而,奇怪的是,类似的设置/代码也适用于我的其他组件。添加依赖项或将代码放入另一个函数 (fetchData()) 并在 useEffect 中调用它不起作用。我还确信这不是规则的问题,因为我以管理员身份访问 Firestore,并为其设置了适当的规则(match/{documents=**} { 允许写入,读取:if request.auth.token.管理==真;})。我不知道发生了什么事。请帮忙。

附注但是,以下代码确实可以在同一组件的 useEffect 中工作,但由于我无法弄清楚如何删除从客户状态中的查询中获得的重复项(尝试过 array.includes 和 indexof 但失败),因为我一直只获得一个相同的对象,我放弃以下代码,转而使用上述代码之一。

const query = firebase.firestore()        
        .collectionGroup('Messages')
        .orderBy("timestamp", "desc")

        const unsub = query.onSnapshot((snapshot) => {

            if (snapshot.empty) {
                console.log('No matching documents.');
                return;
            }  

            snapshot.docs.map((doc) => {                 

                console.log("1")               

                if (customers.length ) {
                    console.log("1b")
                    customers.map((customer) => {
                    console.log("2")
                    if (customer.uid.indexOf(doc.data().uid) === -1) {    
                        console.log("3")                                        
                        setCustomers(prevFiles => ([...prevFiles, {
                                        name: doc.data().name, uid: doc.data().uid
                                }]))
                    } 
                })
                } else  {
                    console.log("4")
                    setCustomers([{name: doc.data().name, uid: doc.data().uid}])                
                }               

                

            });                      
           

        }, (error) => {
            console.log('Error getting messages', error);
        })

最佳答案

我明白了。这对于处于类似情况的人来说可能非常有用,因为 Firestore 文档中似乎没有解释这一点。

无论如何,没有发生任何事情并且 console.logging 不起作用的原因是因为查询为空。因此,请务必检查您的收藏中是否有文档,而这些文档又包含一些信息。我试图获取的文档包含一个集合,并以我需要的用户 ID 命名。然而,由于它们实际上不包含任何信息,因此无法检索。而且,我不知道这一点。我只需要文档的名称、uid。

检查快照是否为空的一种方法如下:

if (snapshot.empty) {
                console.log('No matching documents.');
                return;
            }

在我的代码中,它看起来像这样:

const query = firebase
        .firestore()
        .collection("Chats")
        .get()
        .then((querySnapshot) => {

                if (querySnapshot.empty) {
                console.log('No matching documents.');
                return;
            }

            querySnapshot.forEach((doc) => {

                if (doc.exists) {
                    console.log(doc)
                    setCustomers(prevFiles => ([...prevFiles, {
                    id: doc.data().id, data: doc.data()
                            }]))
                } else {
                    console.log('nothing')
                }
                // doc.data() is never undefined for query doc snapshots
                console.log(doc.id, " => ", doc.data());
            });
        }).catch((error) => {
            console.log("Error getting documents: ", error);
        });

基本上,如果 forEach 部分为空,它永远不会到达。

希望这能澄清人们对集合中的文档可能存在的一些困惑。它们必须包含可检索的信息。快乐编码。

关于reactjs - Firestore get() 和 onSnapshot 函数在 useEffect 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66864459/

相关文章:

javascript - 三次点击作为 React 上的事件?

reactjs - DraftJS Modifier.insertText() : Insert Unicode

java - 如何在带有 firebase 的 android studio 中使用多个过滤器

firebase - Firestore 中的 getDocuments() 和 snapshots() 有什么区别?

reactjs - 是的,验证对象数组最多包含一个对象,其中属性 = 值

javascript - 渲染函数不渲染任何东西 React Native

javascript - 使用 FCM 在前台为浏览器中的每个选项卡接收一个通知

android - 离线时删除 Firebase 存储中的文件

javascript - 使用 Firestore 无限滚动

firebase - 在 firestore 中自动创建集合