我在网络版本中遇到了持久性问题,然后我添加了一个条件来使用不同的持久性,具体取决于它是网络版本还是移动版本。现在的问题是,在移动版本中我收到警告:
警告 [2024-01-18T19:24:16.586Z] @firebase/auth: Auth (10.7.1): 你 正在为 React Native 初始化 Firebase Auth,但不提供 异步存储。身份验证状态将默认为内存持久性并且将 会话之间不会持续存在。为了保持身份验证状态,请安装 包“@react-native-async-storage/async-storage”并提供它 初始化Auth:
导入{initializeAuth,getReactNativePersistence}来自 'firebase/auth';从导入 ReactNativeAsyncStorage '@react-native-async-storage/async-storage';常量授权 = 初始化Auth(应用程序,{持久性: getReactNativePersistence(ReactNativeAsyncStorage) });
这是我的代码:
import { initializeApp } from 'firebase/app';
import {
initializeAuth,
getReactNativePersistence,
browserLocalPersistence,
} from 'firebase/auth';
import { setPersistence } from 'firebase/auth';
import { Platform } from 'react-native';
import ReactNativeAsyncStorage from '@react-native-async-storage/async-storage';
import { getFirestore } from 'firebase/firestore';
// Inicializar Firebase
const firebaseConfig = {
apiKey: process.env.EXPO_PUBLIC_APIKEY,
authDomain: process.env.EXPO_PUBLIC_authDomain,
projectId: process.env.EXPO_PUBLIC_projectId,
storageBucket: process.env.EXPO_PUBLIC_storageBucket,
messagingSenderId: process.env.EXPO_PUBLIC_messagingSenderId,
appId: process.env.EXPO_PUBLIC_appId,
measurementId: process.env.EXPO_PUBLIC_measurementId,
};
export const FIREBASE_APP = initializeApp(firebaseConfig);
export const FIREBASE_DB = getFirestore(FIREBASE_APP);
export const FIREBASE_AUTH = initializeAuth(FIREBASE_APP);
// Conditional persistence configuration
if (Platform.OS !== 'web') {
// settings for (Android/iOS)
const reactNativePersistence = getReactNativePersistence(ReactNativeAsyncStorage);
setPersistence(FIREBASE_AUTH, reactNativePersistence)
.catch((error) => {
console.error('Error with React Native: ', error);
});
} else {
// settings for web
setPersistence(FIREBASE_AUTH, browserLocalPersistence)
.catch((error) => {
console.error('Error with the web: ', error);
});
}
我发现 firebase/auth 中缺少 browserLocalPersistence。
我的解决方案:
import { initializeAuth, getReactNativePersistence } from "firebase/auth";
import ReactNativeAsyncStorage from "@react-native-async-storage/async-storage";
export const FIREBASE_AUTH =
Platform.OS === "web"
? FireAuth.getAuth(FIREBASE_APP)
: initializeAuth(FIREBASE_APP, {
persistence: getReactNativePersistence(ReactNativeAsyncStorage),
});