React Native中Firestore方法未识别,调用时出现ReferenceError求助
解决React Native中Firestore调用的两个错误:
firestore is not defined和process is not defined 1. 修复firestore is not defined错误
Firebase 9+采用模块化API设计,不再支持旧版的firestore()命名空间调用方式,你需要调整代码适配新的API规范:
- 先确认Firebase应用已正确初始化,建议单独创建配置文件(如
firebase.js):
// firebase.js import { initializeApp } from 'firebase/app'; import { getFirestore } from 'firebase/firestore'; // 替换为你的Firebase项目配置 const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_AUTH_DOMAIN", projectId: "YOUR_PROJECT_ID", storageBucket: "YOUR_STORAGE_BUCKET", messagingSenderId: "YOUR_SENDER_ID", appId: "YOUR_APP_ID" }; const app = initializeApp(firebaseConfig); export const db = getFirestore(app);
- 在
Scan.js中导入初始化好的数据库实例,使用addDoc和collection方法替代旧的调用逻辑:
// Scan.js import { db } from './firebase'; // 路径根据你的文件位置调整 import { collection, addDoc } from 'firebase/firestore'; const addProduct = async () => { try { // 替换为你的集合名称和要添加的数据 const docRef = await addDoc(collection(db, 'products'), { productName: '测试商品', scanCode: '123456', createdAt: new Date() }); console.log('数据添加成功,文档ID:', docRef.id); } catch (error) { console.error('添加数据失败:', error); } };
- 注意:确保项目中只安装了
firebase核心包,不要同时安装旧版的@firebase/firestore单独包,避免依赖冲突。
2. 修复process is not defined错误
React Native环境默认不提供Node.js的process全局变量,Firebase部分内部逻辑会依赖它,可通过以下方式解决:
- 安装
process包:
npm install process --save # 或使用yarn yarn add process
- 修改
metro.config.js(项目根目录),添加process的polyfill配置:
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config'); const customConfig = { resolver: { extraNodeModules: { process: require.resolve('process/browser'), }, }, }; module.exports = mergeConfig(getDefaultConfig(__dirname), customConfig);
- (可选)在项目入口文件(如
App.js)顶部添加全局声明,确保process在所有组件中可用:
import process from 'process'; global.process = process;
完成以上调整后,重新启动React Native项目,点击Done按钮应该就能正常连接Firestore并添加数据了。
内容的提问来源于stack exchange,提问作者Linda Sabei
相关产品推荐
相关产品推荐

