Firebase 3.3 实时数据库与 React Native 0.32 卡在 "Making a connection attempt"

Firebase 3.3 realtime database stuck to "Making a connection attempt" with React Native 0.32

firebase@3.3.0

react-native v0.32 在 android 带 wifi 的设备上测试

Firebase 数据库没有任何授权规则,它是开放读写的。

给定以下文件结构:

|_ firebase.js
|_ actions.js

这行不通:

firebase.js

import firebase from 'firebase'

const config = {
    apiKey: "*****",
    authDomain: "****",
    databaseURL: "*****",
    storageBucket: "*****",
}

firebase.database.enableLogging(true);

export default firebase.initializeApp(config)

actions.js

import firebase from './firebase'

export const fetchData = () => {
    const Data = firebase.database().ref('some/data')
    Data.on('value', (snapshot) => {
        console.log("snapshot", snapshot.val())  // never printed
    }, (error) => {
        console.error(error)
    })
}

调试输出

p:0: Browser went online.  
firebase-database.js:36 p:0: Listen called for /some/data default  
firebase-database.js:36 p:0: Making a connection attempt

没有别的...


这确实有效(但不是解决方案) :

firebase.js

...same content as above...

export default () => firebase.initializeApp(config)  // we export a function instead to trigger the initialization when the app is ready

actions.js

...same content as above...
const Data = firebase().database().ref('some/data') // we "manually" trigger the initialization, it's obviously not a good solution since we can't initialize the app multiple times

输出

p:0: Browser went online.  
firebase-database.js:36 p:0: Listen called for /some/data default  
firebase-database.js:36 p:0: Making a connection attempt  
firebase-database.js:36 p:0: Auth token refreshed  
firebase-database.js:36 getToken() completed. Creating connection. 
firebase-database.js:36 c:0:0: Connection created  

我在这里做错了什么?我还注意到,一旦我 import firebase from 'firebase'firebase 变量在所有文件中全局可用,而不是来自 import 语句的 firebase 变量(我可以写 import FooBar from 'firebase' , firebase 全局变量仍然被导入)

因为似乎没有人有 "official" 答案。这是我提供某种惰性初始化的解决方法:

firebase.js

import Firebase from 'firebase'

let _database = null

const initFirebase = () => {
    var config = {
        apiKey: "*************",
        authDomain: "************",
        databaseURL: "**********",
        storageBucket: "************",
    }

    Firebase.database.enableLogging(true)
    Firebase.initializeApp(config)
}

export const getDatabase = () => {
    if (!_database) {
        initFirebase()
        _database = Firebase.database()
    }
    return _database
}

然后,在任何需要 database:

的地方
import { getDatabase } from './firebase'

const methodThatNeedDatabase = () => {
    getDatabase().ref('/some/ref')
    ...
}