[英]ReferenceError: Can't find variable: firebase . I can not connect the App to Firebase from Expo?
我正在嘗試創建一個帶有數據庫的應用程序,我將在 Cloud Firestore 中添加幾個 collections。 但這是不可能的,因為當我添加連接應用程序的代碼時應用程序被破壞了。
我在 Stack 和 GitHub 上看到了各種解決方案,但是經過幾個小時的測試,它不起作用。
Firebase v9 modular - 找不到變量:IDBIndex
https://github.com/expo/expo/issues/8089
目前應用非常簡單,Firebase中只涉及兩個文件,沒有任何作用
我已經通過幾種方式更改了調用 Firebase 的方式:
import firebase from 'firebase/app'
import 'firebase/firestore'
import {initializeApp} from 'firebase/app'
import 'firebase/firestore'
import firebase from 'firebase/compat/app'
import 'firebase/compat/firestore'
目前我的代碼如下:
import firebase from 'firebase/app'
import 'firebase/firestore'
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxx",
appId: "xxxxxxxxxxx"
}
export const firebaseApp = firebase.initializeApp(firebaseConfig)
文件actions.js
import { firebaseApp } from "./firebase"
import firebase from 'firebase/app'
import 'firebase/firestore'
const db = firebase.firestore(firebaseApp)
export const isUserLogged = () => {
let isLogged = false
firebase.auth().onAuthStateChanged((user)=> {
user !== null && (isLogged = true)
})
return isLogged
}
以及控制台向我顯示的錯誤:
**
TypeError: undefined is not an object (evaluating '_app.default.initializeApp')
- ... 9 more stack frames from framework internals
Invariant Violation: "main" has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called.
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:104:6 in reportException
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:172:19 in handleException
at node_modules/react-native/Libraries/Core/setUpErrorHandling.js:24:6 in handleError
at node_modules/@react-native/polyfills/error-guard.js:49:36 in ErrorUtils.reportFatalError
**
我該如何糾正這個錯誤?
您正在從較新的模塊化 SDK 導入函數,但隨后嘗試調用較舊的命名空間 API。 那行不通的。
我建議使用web 上的 Firebase 身份驗證入門的代碼示例, 獲取當前登錄的用戶和升級指南。
使用新的模塊化語法,您可以構建一個 function,它返回一個 promise,第一個身份驗證為 state,其中:
import { initializeApp } from "firebase/app";
import { getAuth, onAuthStateChanged } from "firebase/auth";
const firebaseConfig = {
// ...
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
export const isUserLogged = () => {
return new Promise((resolve, reject) => {
let unsubcribe = onAuthStateChanged(auth, (user) => {
unsubcribe();
resolve(user !== null)
})
});
}
如果你想堅持使用命名空間 API,你可以導入舊版本的 Firebase(例如最新的 v8 版本)或使用新的 SDK 的兼容路徑,在我上面鏈接的同一升級指南中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.