React-Native-Firebase:RTDB 模拟器

React-Native-Firebase : RTDB Emulator

有人知道如何使用实时数据库模拟器吗?

我可以像下面这样使用函数和 firestore 模拟器。

import functions from '@react-native-firebase/functions';
import firestore from '@react-native-firebase/firestore';

functions().useFunctionsEmulator('http://localhost:5001');
firestore().settings({ host: 'localhost:8080' });

但无法为实时数据库找到类似的东西。 任何 link/video 表示赞赏。

谢谢。

根据 Connect your app to the Realtime Database Emulator 上的文档,这是通过以下方式完成的:

if (location.hostname === "localhost") {

  var firebaseConfig = {
    // Point to the RTDB emulator running on localhost.
    // In almost all cases the ns (namespace) is your project ID.
    databaseURL: "http://localhost:9000?ns=YOUR_DATABASE_NAMESPACE"
  }

  var myApp = firebase.initializeApp(firebaseConfig);
  var db = myApp.database();
} 

我不确定 react-native-firebase 是否支持它,因为他们的文档中根本没有提到它。最合乎逻辑的尝试是他们的 Using a secondary database:

const database = firebase.app().database('http://localhost:9000?ns=YOUR_DATABASE_NAMESPACE');

基本上Frank van Puffelen发布的解决方案是正确的。但是,这让我卡住了一段时间,所以我将分享我的经验,以节省其他人的时间。

import { firebase } from "@react-native-firebase/database";
const database = firebase
  .app()
  .database("http://localhost:9000?ns=YOUR_DATABASE_NAMESPACE");
const ref = database.ref(`yourPath`)
...

这里有一个巨大的陷阱: 如果您使用的是 Android 模拟器,则必须使用

const database = firebase
  .app()
  .database("http://10.0.2.2:9000?ns=YOUR_DATABASE_NAMESPACE");

如果您使用的是真正的 android 设备,则必须先设置 reverse proxy

adb reverse tcp:9000 tcp:9000

然后正常设置数据库

const database = firebase
  .app()
  .database("http://localhost:9000?ns=YOUR_DATABASE_NAMESPACE");

我没有测试 iOS,但我相信 localhost 应该可以。

我的根 index.js 文件中有这个用于我的 React Native 项目:

// Use a local emulator in development
if (__DEV__) {
  // If you are running on a physical device, replace http://localhost with the local ip of your PC. (http://192.168.x.x)
  auth().useEmulator('http://localhost:9099');
  functions().useFunctionsEmulator('http://localhost:5001');
  database().useEmulator('localhost', 9000);

  const db = firestore();
  db.settings({ host: 'localhost:8080', ssl: false });
}

我的应用程序中没有其他内容需要修改。 database().useEmulator 行就可以了。

我假设您已经首先使用 firebase init emulators 初始化了所有模拟器并让它们 运行 firebase emulators:start.

确保您在模拟器中使用 ${projectId}-default-rtdb 数据库。