Expo React Native中Firebase Firestore报错求助
解决Expo项目中Firestore初始化错误的方案
问题原因
@react-native-firebase/firestore 是针对裸React Native项目的依赖,需要手动配置原生Android/iOS工程(比如修改MainApplication.java),但Expo Managed Workflow不允许直接操作原生文件,因此会触发该错误。
解决步骤
1. 卸载不兼容的依赖
执行命令移除@react-native-firebase/firestore:
npm uninstall @react-native-firebase/firestore # 或使用yarn yarn remove @react-native-firebase/firestore
2. 安装Expo官方Firebase依赖
Expo提供了适配Managed Workflow的Firebase集成包,安装核心包和Firestore模块:
npx expo install expo-firebase-core expo-firebase-firestore
3. 配置Firebase项目
在Expo项目的app.json或app.config.js中添加Firebase配置(从Firebase控制台获取你的项目配置):
{ "expo": { "ios": { "googleServicesFile": "./GoogleService-Info.plist" }, "android": { "googleServicesFile": "./google-services.json" }, "web": { "config": { "firebase": { "apiKey": "YOUR_API_KEY", "authDomain": "YOUR_AUTH_DOMAIN", "projectId": "YOUR_PROJECT_ID", "storageBucket": "YOUR_STORAGE_BUCKET", "messagingSenderId": "YOUR_MESSAGING_SENDER_ID", "appId": "YOUR_APP_ID" } } } } }
注意:iOS和Android需要从Firebase控制台下载对应的GoogleService-Info.plist和google-services.json文件,放到项目根目录。
4. 修改Firestore调用代码
替换原有代码为Expo兼容的写法:
import firebase from 'expo-firebase-app'; import 'expo-firebase-firestore'; // 若未自动初始化则手动初始化 if (!firebase.apps.length) { firebase.initializeApp(firebase.app().options); } const UserInfo = firebase.firestore().collection("UserInfo");
替代方案:使用Firebase Web SDK
如果不想用Expo的Firebase包,也可以直接用Firebase Web SDK,无需原生配置:
- 安装web版SDK:
npm install firebase # 或yarn add firebase
- 初始化并使用:
import { initializeApp } from 'firebase/app'; import { getFirestore, collection } from 'firebase/firestore'; const firebaseConfig = { // 填入你的Firebase项目配置 }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); const UserInfo = collection(db, "UserInfo");
内容的提问来源于stack exchange,提问作者Gustavo de Araujo
相关产品推荐
相关产品推荐

