如何在React中使用Modular SDK访问Firestore文档?
Firebase Modular SDK 迁移问题解决方案
1. 「Module not found. Unable to resolve 'firebase'」报错解决
- 先确认你安装了V9及以上版本的Firebase SDK,执行安装命令:
npm install firebase
如果之前装过旧版可以先卸载再重装避免冲突:npm uninstall firebase && npm install firebase - 确认初始化代码用的是模块化导入写法,不能用旧版命名空间导入,示例如下:
// 你的firebase初始化文件,比如src/firebase/config.js import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore"; // 替换为你自己项目的Firebase配置 const firebaseConfig = { apiKey: "xxx", authDomain: "xxx", projectId: "xxx", storageBucket: "xxx", messagingSenderId: "xxx", appId: "xxx" }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); export default db;
不要使用import firebase from 'firebase'这类旧版导入语法,是V9+版本不再支持的写法。
2. 查询返回undefined、调用data()方法报错解决
你当前代码的问题在于:getDocs返回的是集合的查询快照对象,本身没有data()方法,data()是单个文档实例的方法,需要遍历快照内的docs数组处理每个文档。
另外你旧版用的是onSnapshot实时监听逻辑,你现在写的getDocs是一次性拉取逻辑,两种场景的正确写法分别如下:
场景1:一次性拉取posts集合所有文档
import { collection, getDocs } from "firebase/firestore"; import db from "你的firebase初始化文件路径"; // ...你的组件其他代码 useEffect(() => { const fetchPosts = async () => { const postsColRef = collection(db, 'posts'); const postsSnapshot = await getDocs(postsColRef); const postsList = postsSnapshot.docs.map(doc => ({ id: doc.id, // 建议携带文档id,后续修改删除文档都需要用到 ...doc.data() })); setPosts(postsList); }; fetchPosts(); }, []);
场景2:保持和旧版一致的实时监听效果
import { collection, onSnapshot } from "firebase/firestore"; import db from "你的firebase初始化文件路径"; // ...你的组件其他代码 useEffect(() => { const postsColRef = collection(db, 'posts'); // onSnapshot返回取消监听的函数,需要在组件卸载时调用避免内存泄漏 const unsubscribe = onSnapshot(postsColRef, (snapshot) => { setPosts(snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }))); }); // 清理函数 return () => unsubscribe(); }, []);
注意所有用到的Firebase方法都要从firebase/firestore导入,未导入也会触发运行时报错。
内容的提问来源于stack exchange,提问作者Dan Shawl
相关产品推荐
相关产品推荐

