React集成Firebase9调用db.collection提示is not a function问题求助
问题原因
Firebase v9 采用模块化API设计,移除了旧版本中db实例上挂载的collection、doc等链式调用方法,所有操作都需要通过从firebase/firestore导入的顶级函数完成。你当前代码中仍然使用v8及更早版本的db.collection()链式写法,没有用到已导入的collection、doc方法,所以会同时出现导入灰显和运行时报错的问题。
解决方案
方案1:使用标准模块化API(官方推荐)
修改databaseservice.js代码,替换为v9的函数式写法即可,注意新增导入getDoc方法:
import { db } from './config'; import { doc, getDoc } from 'firebase/firestore'; export const getChapters = (scanId) => { // 构造文档引用 const docRef = doc(db, 'somecollection', scanId); // 读取文档 getDoc(docRef) .then((docSnap) => { if (docSnap.exists()) { console.log('Document data:', docSnap.data()); } else { console.log('No such document!'); } }) .catch((error) => { console.log('Error getting document:', error); }); };
方案2:正确使用compat版本兼容旧写法
如果要保留原有链式调用写法,需要确保所有Firebase相关导入都使用compat路径,不要混用标准模块化版本和compat版本,之前compat版本报错基本都是导入路径混用导致的:
- 修改
config.js代码:
import firebase from 'firebase/compat/app'; import 'firebase/compat/firestore'; const firebaseConfig = { apiKey: '****', authDomain: '*****', projectId: '*****', storageBucket: '*****', messagingSenderId: '****', appId: '*****', }; const app = firebase.initializeApp(firebaseConfig); export const db = app.firestore();
- 原有
databaseservice.js中的db.collection()链式写法可直接正常使用。
内容的提问来源于stack exchange,提问作者wick3d
相关产品推荐
相关产品推荐

