【问题标题】:What is the purpose of calling firebase.app() in react native firebase?在 react native firebase 中调用 firebase.app() 的目的是什么?
【发布时间】:2017-10-04 03:39:01
【问题描述】:

我尝试了所有工作。有什么区别?

import firebase from 'react-native-firebase';

const defaultApp = firebase.app();

defaultApp.database().ref('foobar').once('value', (snapshot) => {
  // snapshot from default app
});

import firebase from 'react-native-firebase';

firebase.database().ref('foobar').once('value', (snapshot) => {
  // snapshot from default app
});

【问题讨论】:

    标签: javascript firebase react-native react-native-firebase


    【解决方案1】:

    这两种方法是等价的。第二个只是依赖于一些硬编码的默认值,而第一个更明确。如果您想(例如)在单​​个应用程序中访问数据库,这一点尤其明显。

    我们的documentation explains this rather well,所以我会从那里引用:

    在大多数情况下,您只需初始化一个默认应用程序。您可以通过两种等效方式从该应用访问服务:

    // Initialize the default app
    var defaultApp = firebase.initializeApp(defaultAppConfig);
    
    console.log(defaultApp.name);  // "[DEFAULT]"
    
    // You can retrieve services via the defaultApp variable...
    var defaultStorage = defaultApp.storage();
    var defaultDatabase = defaultApp.database();
    
    // ... or you can use the equivalent shorthand notation
    defaultStorage = firebase.storage();
    defaultDatabase = firebase.database();
    

    某些用例要求您同时创建多个应用。例如,您可能希望从一个 Firebase 项目的实时数据库中读取数据并将文件存储在另一个项目中。或者,您可能希望对一个应用程序进行身份验证,同时让另一个应用程序未经身份验证。 Firebase SDK 允许您同时创建多个应用,每个应用都有自己的配置信息。

    // Initialize the default app
    firebase.initializeApp(defaultAppConfig);
    
    // Initialize another app with a different config
    var otherApp = firebase.initializeApp(otherAppConfig, "other");
    
    console.log(firebase.app().name);  // "[DEFAULT]"
    console.log(otherApp.name);        // "other"
    
    // Use the shorthand notation to retrieve the default app's services
    var defaultStorage = firebase.storage();
    var defaultDatabase = firebase.database();
    
    // Use the otherApp variable to retrieve the other app's services
    var otherStorage = otherApp.storage();
    var otherDatabase = otherApp.database();
    

    注意:每个应用实例都有自己的配置选项和身份验证状态。

    【讨论】:

    • 一针见血,只是为了补充一点,在 react-native-firebase 中,默认应用程序通过谷歌在本地对应部分 firebase sdk(ios 和 android)上预初始化服务 json/plist 文件,因此默认应用程序不需要 initializeApp - 它仍然允许您调用它,但在内部它会忽略所有传递的选项并返回已初始化的应用程序(带有弃用警告)。这将在未来的版本中更改为抛出“默认应用程序已初始化”错误 - 与 web sdk 相同。免责声明:RNFirebase 的作者
    【解决方案2】:

    您不需要调用该方法,除非您在应用程序中使用多个 Firebase 应用程序实例

    【讨论】:

      猜你喜欢
      • 2022-01-06
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多