将 firestore 从 v8 集成到 v9

integrate firestore from v8 to v9

我想在“频道”集合中检索我的子集合“消息”并将它们显示在我的聊天页面上。我尝试了不同的策略,比如 useEffect 但没有结果。

如何将这行代码从 v8 更改为 v9?:

const [messages] = useCollection(
channelId &&
    db
.doc(channelId)
.collection("messages")
.orderBy("timestamp", "asc")
  );

消息显示部分:

<div>
  {messages?.docs.map((doc) => {
 const { message, timestamp, name, photoURL, email } = doc.data();
 return (
 <Message
          key={doc.id}
          id={doc.id}
          message={message}
          timestamp={timestamp}
          name={name}
          email={email}
          photoURL={photoURL}
        />
 );
 })}
</div>

我可以向 firestore 发送消息,但无法显示它。每次我通过消息映射时,我的应用程序都会变成空白。

如果你想在不需要 useEffect 钩子的情况下检索数据。

执行如下查询:


    const collectionRef = query(
        collection(db, `channels/${channelId}/messages`),
        orderBy("timestamp", "asc"));
    
    const messageDocs = await collectionRef.get() // this is only the docs
    
    // to get the doc data you will need to map each doc to its data
    
    const messageDocsData = messageDocs.map((doc) => doc.data()) 

如果您希望您的数据在 UI 随着数据库的更新而改变,您将需要 useEffect:

    const [messageDocsData, setMessageDocsData] = useState([]);

    const collectionRef = query(
        collection(db, `channels/${channelId}/messages`),
        orderBy("timestamp", "asc"));

    useEffect(() => {
       const unsubscribe = onSnapshot(collectionRef, (querySnapshot) =>
      setMessageDocsData(querySnapshot.docs.map((doc) => doc.data()))
    );

    return () => unsubscribe();
    }, []);
    
   // messageDocsData will now always have the latest snapshot of the documents