gpt4 book ai didi

Firebase 3.3 实时数据库使用 React Native 0.32 停留在 "Making a connection attempt"

转载 作者:行者123 更新时间:2023-12-02 21:20:56 26 4
gpt4 key购买 nike

firebase@3.3.0

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

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变量在除 firebase 之外的所有文件中全局可用。来自 import 语句的 var (我可以写 import FooBar from 'firebase'firebase 全局 var 仍然被导入)

最佳答案

因为似乎没有人有“官方”答案。这是我提供某种延迟初始化的解决方法:

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
}

然后,在您需要数据库的任何地方:

import { getDatabase } from './firebase'

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

关于Firebase 3.3 实时数据库使用 React Native 0.32 停留在 "Making a connection attempt",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39152898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com