× FirebaseError:collection() 的第一个参数预计为 CollectionReference、DocumentReference 或 FirebaseFirestore



嗨,我有这个代码,我有使用firebase v9 web。下面是我的代码:

const [post, setPosts] = useState([]);
useEffect(() => {
const q = query(collection(db, "posts"));
onSnapshot(q, (querySnapshot) => {
setPosts(
querySnapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() }))
);
});
});

文档中有V8名称间隔语法和V9模块语法的示例:

import { getFirestore, collection, query, where, onSnapshot } from "firebase/firestore";
const db = getFirestore()
const q = query(collection(db, "posts"));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
setPosts(querySnapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() })))
});

我用来创建firebaseApp,我可以稍后在应用程序中使用。自从firebase@9我得到了同样的错误。现在我在数据库调用之前创建firebaseApp,这似乎可以工作。

const [post, setPosts] = useState([]);
useEffect(() => {
const app = initializeApp(firebaseOption);
const db = getFirestore(app);
const q = query(collection(db, "posts"));
onSnapshot(q, (querySnapshot) => {
setPosts(
querySnapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() }))
);
});
});

相关内容

  • 没有找到相关文章

最新更新