简体   繁体   English

如何在 onSnapshot() 中使用 orderBy() 以便我可以根据时间戳对文档进行排序?

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

So basically please tell me how I should implement the orderBy() function of firestore in onSnapshot() in React.所以基本上请告诉我应该如何在 React 的 onSnapshot() 中实现 firestore 的 orderBy() function。 Please help me, guys.请帮助我,伙计们。 I really need your help.我真的需要你的帮助。 If your answering my question please share this code with the orderBy() function implement in it.如果您回答了我的问题,请与其中的 orderBy() function 工具分享此代码。 Here is my code -这是我的代码 -

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

and I have returned this我已经归还了这个

<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> 
      )
    } )}

Instead of a "simple" CollectionReference , you can pass a Query to the onSnaphot() Function, as follows.您可以将Query传递给onSnaphot() Function,而不是“简单的” CollectionReference ,如下所示。 You'll find more details in the Firestore documentation .您将在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 })))
})

Note: Actually a CollectionReference extends a Query .注意:实际上CollectionReference扩展了Query

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM