Firebase登录状态页面跳转:登录后跳转新页面,登出返回登录页
Firebase Authentication 登录/登出页面跳转实现
登录成功后跳转
在登录逻辑的成功回调中添加页面跳转代码即可,以下是两种常见场景的实现:
原生 JavaScript 环境
// 登录逻辑 firebase.auth().signInWithEmailAndPassword(email, password) .then((userCredential) => { // 登录成功,跳转到目标页面(示例为主页) window.location.href = '/home.html'; }) .catch((error) => { // 处理登录错误 console.error(error.code, error.message); });
React 环境(搭配 react-router-dom)
import { useNavigate } from 'react-router-dom'; import { getAuth, signInWithEmailAndPassword } from 'firebase/auth'; const LoginPage = () => { const navigate = useNavigate(); const auth = getAuth(); const handleLogin = async (email, password) => { try { await signInWithEmailAndPassword(auth, email, password); // 登录成功跳转到主页 navigate('/home'); } catch (error) { console.error(error.code, error.message); } }; // 组件其余逻辑... };
登出成功后跳转
在登出逻辑的成功回调中添加跳转回登录页的代码:
原生 JavaScript 环境
// 登出逻辑 firebase.auth().signOut() .then(() => { // 登出成功,跳转回登录页 window.location.href = '/login.html'; }) .catch((error) => { console.error(error.code, error.message); });
React 环境(搭配 react-router-dom)
import { useNavigate } from 'react-router-dom'; import { getAuth, signOut } from 'firebase/auth'; const HomePage = () => { const navigate = useNavigate(); const auth = getAuth(); const handleLogout = async () => { try { await signOut(auth); // 登出成功跳转回登录页 navigate('/login'); } catch (error) { console.error(error.code, error.message); } }; // 组件其余逻辑... };
监听认证状态自动跳转(可选)
为了处理页面刷新或直接访问页面的情况,可以监听用户认证状态变化,自动完成跳转:
原生 JavaScript 环境
firebase.auth().onAuthStateChanged((user) => { const currentPath = window.location.pathname; if (user) { // 用户已登录,若当前在登录页则跳转到主页 if (currentPath === '/login.html') { window.location.href = '/home.html'; } } else { // 用户未登录,若当前不在登录页则跳转回登录页 if (currentPath !== '/login.html') { window.location.href = '/login.html'; } } });
React 环境(全局监听)
可在路由配置或根组件中添加监听:
import { useEffect } from 'react'; import { useNavigate, useLocation } from 'react-router-dom'; import { getAuth, onAuthStateChanged } from 'firebase/auth'; const AuthListener = () => { const navigate = useNavigate(); const location = useLocation(); const auth = getAuth(); useEffect(() => { const unsubscribe = onAuthStateChanged(auth, (user) => { if (user) { // 已登录,若当前在登录页则跳转主页 if (location.pathname === '/login') { navigate('/home'); } } else { // 未登录,若当前不在登录页则跳转登录页 if (location.pathname !== '/login') { navigate('/login'); } } }); return unsubscribe; // 清理监听 }, [auth, navigate, location]); return null; }; // 在根组件中引入监听组件 function App() { return ( <div> <AuthListener /> {/* 路由配置... */} </div> ); }
内容的提问来源于stack exchange,提问作者Abdulhameed Mustapha
相关产品推荐
相关产品推荐

