我正在开发一个聊天消息功能,但在我的控制台中遇到了这个错误:messagesRef.orderBy is not a function
下面是我目前的代码:
消防基地.js
import firebase from 'firebase/compat/app'
import 'firebase/compat/auth'
import "firebase/compat/storage";
import { getStorage } from "firebase/storage";
import { getFirestore } from "firebase/firestore"
const app = firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGE_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID
})
export const auth = app.auth()
export const storage = getStorage(app);
export const db = getFirestore(app);
export default app
Messages.jsx
import React, { useState, useEffect } from "react";
import { auth, db } from "../firebase"
import { collection, getDocs } from "firebase/firestore";
const Messaging = () => {
const [user, setUser] = useState(null);
const [text, setText] = useState("");
const [messages, setMessages] = useState([]);
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((user) => {
if (user) {
setUser(user);
} else {
setUser(null);
}
});
const messagesRef = collection(db, "messages");
messagesRef.orderBy("createdAt").onSnapshot((snapshot) => {
const messagesList = snapshot.docs.map((doc) => ({
...doc.data(),
id: doc.id,
}));
setMessages(messagesList);
});
return () => {
unsubscribe();
};
}, []);
const handleTextChange = (e) => {
setText(e.target.value);
};
const handleSend = () => {
const newMessage = {
text,
createdAt: new Date(),
userId: user.uid,
};
db.collection("messages").add(newMessage);
setText("");
};
return (
<>
<div>
{user ? (
<div>
<div>
{messages.map((message) => (
<div key={message.id}>
<p>{message.text}</p>
</div>
))}
</div>
<div>
<input value={text} onChange={handleTextChange} />
<button onClick={handleSend}>Send</button>
</div>
</div>
) : (
<button onClick={() => auth.signInAnonymously()}>Sign In</button>
)}
</div>
</>
);
};
export default Messaging;
我的假设是集合没有被正确导入,但是我已经尝试了collection(db, "messages")
和db.collection("messages")
,我不确定从哪里开始。
感谢您的任何输入您可能有!
此外,我已经知道我不应该导入/compat库,但我得到一个错误,没有它,所以这是没有改变。
1条答案
按热度按时间dfty9e191#
您正在从新的(ish)模块化SDK导入
getFirestore
,这意味着像orderBy
这样的功能是一个顶级函数,而不是引用上的方法。因此,如果我们遵循文档中关于排序数据的代码示例,这意味着您的代码应该是: