我有一个应用程序,想要做到这一点,当应用程序启动时,它会检查用户是否设置了一个状态,表明他们想要保持登录状态。如果他们这样做了,它会将他们带到主屏幕,如果他们没有这样做将他们带到正常的启动页面。我有这个:
const app = initializeApp(firebaseConfig);
const auth = initializeAuth(app, {
persistence: getReactNativePersistence(AsyncStorage),
});
useEffect(() => {
const checkAuthStatus = async () => {
try {
const staySignedIn = await AsyncStorage.getItem("staySignedIn");
const authInstance = getAuth();
const user = authInstance.currentUser;
const lastLoginTime = await AsyncStorage.getItem("lastLoginTime");
if (lastLoginTime) {
const currentTime = new Date();
const lastLoginDate = new Date(lastLoginTime);
const diffInTime = currentTime - lastLoginDate;
const diffInDays = diffInTime / (1000 * 3600 * 24);
if (diffInDays > 90) {
await signOut(authInstance);
await AsyncStorage.removeItem("lastLoginTime");
await AsyncStorage.removeItem("staySignedIn");
setLoading(false);
return;
}
}
if (staySignedIn === "true" && user) {
router.push("/(tabs)/shared/Home");
} else {
setLoading(false);
}
} catch (error) {
console.error("Error checking authentication status:", error);
setLoading(false);
}
};
checkAuthStatus();
}, []);
`
Firebase 似乎需要大约 0.03 秒才能获取用户......比我的组件安装所需的时间还要长。这意味着即使有用户,它也会为他们返回 null。我考虑过监听身份验证中的状态更改,但问题是,如果用户实际上为空,则状态不会更改,然后下次状态更改时(假设他们点击了应该的注册按钮)将他们带到 otp 屏幕)它将表现得好像他们是登录用户并将他们带到主屏幕。除了增加延迟之外我还能做些什么吗?
我试图让选择保持登录状态的用户登录,而不更改我的应用程序的任何其他功能。
我考虑过监听身份验证中的状态变化
这是正确的做法。
问题是如果用户实际上是null
这是预期的 - currentUser 为 null,直到 Firebase 能够验证用户之前保留的令牌。
除了增加延迟之外我还能做些什么吗?
侦听器是正确的方法。您可以最初显示某种旋转器或其他隐式延迟组件,该组件将持续到侦听器为您提供用户对象或 null。 此时,您知道您可以从微调器切换到导航到已登录用户应该去的位置,或者要求他们登录。