[英]ReactNative initialize Firebase at app start?
我有一個 app.js 文件,在其中創建我的NavigationContainer
並添加一些屏幕並調用名為init
的 function (來自我的 firebase.js 文件,見下文)為 Z0354Z89.48D092414FAAF9349 初始化我的應用程序
我還有一個 LoginScreen.js 文件,我在其中使用 firebase 處理登錄/注冊過程。 如果用戶已登錄,應用程序會立即加載 HomeScreen.js 文件。 firebase 配置位於一個單獨的文件 (firebase.js) 中,如下所示:
// Import the functions you need from the SDKs you need
import { initializeApp } from 'firebase/app'
import { getDatabase } from 'firebase/database'
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
// Imagine a config file here //
};
const init = () => {
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
}
export { init };
// somehow need to export db here
我現在在用戶可以從我的主屏幕導航到的新屏幕中添加待辦事項列表。 在這里,我需要 firebase.js 中的數據庫,因為我想將對象保存在那里。 但是,db 似乎是“未定義的”,可能是因為我沒有從 firebase.js 文件中導出它,所以我無法訪問它。
我嘗試從我的 app.js 中刪除 init function,但這會引發“未創建 Firebase 應用程序”問題。
問題:如何在 firebase.js 中初始化我的應用程序,確保首先調用它並在同一個 firebase.js 文件中導出工作數據庫?
我找到了一種方法(以防萬一這對將來的任何人有幫助):只需刪除 init function 並導出應用程序和數據庫,如下所示:
// Import the functions you need from the SDKs you need
import { initializeApp } from 'firebase/app'
import { getDatabase } from 'firebase/database'
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
//imagine config here
};
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
export { app, db };
然后,在 app.js 文件中從 firebase.js 導入app
並調用它,如下所示:
import { app } from './firebase';
{ /* this calls the firebase.js and initializes the app */ }
app
export default function App() { ... }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.