React useState 和 Firebase onSnapshot

Mar*_*ler 2 javascript firebase reactjs google-cloud-firestore react-hooks

我想使用 onSnapshot 自动从 firestore 集合中获取新传入消息。虽然我可以在回调中设置状态,但我无法读取它。

const [messages, setMessages] = useState(null);
const [chat, setChat] = useState(props.chatId);

useEffect(() => {
        const q = query(collection(db, "messages"), where("chat_id", "==", chat), orderBy("date","desc"), limit(5));
        // Create the DB listener
        const unsuscribe = onSnapshot(q, (querySnapshot) => {
            console.log(messages);
            if(messages === null){
                console.log("setting messages the first time");
                setMessages(querySnapshot.docs)
            }else{
                console.log("updating messages");
                setMessages([...querySnapshot.docs, ...messages])
            }
        });
        return () => {
            console.log("unsubscribe");
            unsuscribe();
        }
    }, [chat]);
Run Code Online (Sandbox Code Playgroud)

每当onSnapshot触发时,messages总是有效nullsetMessages因为显示了消息。我尝试了很多方法但无法使其发挥作用。

非常感谢帮助。

Mar*_*ler 10

所以我设法找到了解决方案。诀窍是监听消息的状态变化useEffect()

const [snapShot, setSnapshot] = useState(null);
const [messages, setMessages] = useState(null);
const [chat, setChat] = useState(props.chatId);

useEffect(() => {
        const q = query(collection(db, "messages"), where("chat_id", "==", chat), orderBy("date","desc"), limit(5));
       
        const unsuscribe = onSnapshot(q, (querySnapshot) => {
            setSnapShot(querySnapshot)
        });
        return () => {
            unsuscribe();
        }
    }, [chat]);

useEffect(() => {
  if(messages === null){
                console.log("setting messages the first time");
                setMessages(snapShot.docs)
            }else{
                console.log("updating messages");
                setMessages([...snapShot.docs, ...messages])
            }
    }, [snapShot]);
Run Code Online (Sandbox Code Playgroud)