簡體   English   中英

如何在 onSnapshot() 中使用 orderBy() 以便我可以根據時間戳對文檔進行排序?

[英]how to use orderBy() in onSnapshot() so I can order the documents on the basis of the timestamp?

所以基本上請告訴我應該如何在 React 的 onSnapshot() 中實現 firestore 的 orderBy() function。 請幫助我,伙計們。 我真的需要你的幫助。 如果您回答了我的問題,請與其中的 orderBy() function 工具分享此代碼。 這是我的代碼 -

onSnapshot(collection(db, "messages"), (snapshot) => {
setMessages(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id})))
 })

我已經歸還了這個

<div className="chat-app">
    {messages && messages.map((msg) => {
      return (
        <div key={msg.id} className="message">
          <img className="img" src={msg.image}></img>
          <div className="msg">{msg.message}</div>
        </div> 
      )
    } )}

您可以將Query傳遞給onSnaphot() Function,而不是“簡單的” CollectionReference ,如下所示。 您將在Firestore 文檔中找到更多詳細信息。

import { ..., collection, query, orderBy} from "firebase/firestore";  

const q = query(collection(db, "messages"), orderBy("xyz"));
onSnapshot(q, (snapshot) => {
    setMessages(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
})

注意:實際上CollectionReference擴展了Query

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM