我希望在“頻道”集合中檢索我的子集合“訊息”并將它們顯示在我的聊天頁面上。我嘗試了不同的策略,比如 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 發送訊息,但讓它顯示一直是個問題。每次我通過訊息映射時,我的應用程式都會變為空白。
uj5u.com熱心網友回復:
如果您想在不需要 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/449597.html
