React Vite+Firebase聊天应用报错:db.collection不是函数求助
解决Firestore中'db.collection is not a function'报错问题
你遇到的问题是因为使用了Firebase v9+的模块化SDK,它采用了函数式API设计,不再支持旧版SDK的db.collection()链式调用写法。
修复步骤:
补充导入
collection函数
在Firestore的导入语句中添加collection:import React from "react"; import "./App.css"; import { initializeApp } from "firebase/app"; // 新增collection导入 import { getFirestore, collection } from "firebase/firestore"; import { useCollectionData } from "react-firebase-hooks/firestore"; import { getAuth, GoogleAuthProvider, signInWithPopup, signOut, } from "firebase/auth";替换集合引用的创建方式
将db.collection('messages')改为使用collection函数:const ChatRoom = () => { // 用collection函数创建集合引用 const messagesRef = collection(db, 'messages'); const [user] = useAuthState(auth); return ( <div> <h1>Chat Room</h1> <p>Welcome {user.displayName}</p> <button onClick={LogOut}>Sign Out</button> </div> ) }
扩展说明(若后续需要查询操作)
如果要对集合进行排序、过滤等查询操作,需要导入query和对应的条件函数(比如orderBy),示例:
import { getFirestore, collection, query, orderBy } from "firebase/firestore"; // 在组件内构建查询 const messagesQuery = query(collection(db, 'messages'), orderBy('createdAt')); const [messages] = useCollectionData(messagesQuery);
内容的提问来源于stack exchange,提问作者Kevin Anthony
相关产品推荐
相关产品推荐

