我希望在“通道”集合中检索我的子集合“消息”,并将它们显示在我的聊天页面上。我尝试过像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>我可以发送信息到消防局,但让它显示一直是一个问题。每次我通过信息地图,我的应用程序变成空白。
发布于 2022-03-24 21:29:11
如果您想在不需要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()) 如果希望在更新数据库时用户界面上的数据发生更改,则需要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 documentshttps://stackoverflow.com/questions/71586941
复制相似问题