You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native集成Firebase实时数据库报错,如何解决?

解决Expo + React Native Firebase实时数据库报错问题

核心问题原因

你用的是Expo项目,但按照原生React Native的Firebase文档配置,导致原生模块未正确集成——Expo托管项目不允许手动修改MainApplication.java这类原生文件,而@react-native-firebase库需要原生层支持,因此出现该错误。

两种解决方案

方案一:改用Expo官方Firebase库(适合托管项目,无需修改原生代码)

  1. 卸载现有@react-native-firebase依赖
    npm uninstall @react-native-firebase/app @react-native-firebase/database
    
  2. 安装Expo官方Firebase核心及数据库模块
    npx expo install expo-firebase-core expo-firebase-database
    
  3. 配置app.json/app.config.js
    将以下配置添加到expo字段中(确保google-services.json放在项目根目录):
    "android": {
      "googleServicesFile": "./google-services.json"
    },
    "plugins": [
      [
        "expo-firebase-core",
        {
          "firebaseJsonPath": "./firebase.json"
        }
      ]
    ]
    
  4. 修改代码适配Expo Firebase API
    import Firebase from 'expo-firebase-app';
    import 'expo-firebase-database';
    
    const Categories = () => {
      // 注意修正URL里的拼写错误:euorpe-west1 → europe-west1
      const reference = Firebase.database('https://testapp-app-default-rtdb.europe-west1.firebasedatabase.app/').ref('/categories');
      
      // 示例:读取数据
      reference.on('value', (snapshot) => {
        const data = snapshot.val();
        console.log('分类数据:', data);
      });
    };
    

方案二:将Expo转为预构建项目(支持@react-native-firebase)

如果坚持使用@react-native-firebase库,需要生成原生项目文件:

  1. 执行预构建命令(生成Android/iOS原生目录)
    npx expo prebuild
    
  2. 移动google-services.json到android/app目录下
  3. 重新安装依赖并清除缓存启动
    npm install @react-native-firebase/app @react-native-firebase/database
    npx expo start --clear
    
    预构建会自动处理MainApplication.java的配置,无需手动修改。

额外注意事项

  • 检查实时数据库URL拼写:你代码里的euorpe-west1是拼写错误,应改为europe-west1,否则会连接失败
  • 确保Firebase控制台已启用实时数据库,测试阶段可临时设置规则为:
    {
      "rules": {
        ".read": true,
        ".write": true
      }
    }
    
    上线前务必修改为安全的权限规则

内容的提问来源于stack exchange,提问作者frak01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 02:18:11