React-Redux与Firebase登出后路由未跳转问题求助
React-Redux + Firebase 登出后页面未跳转问题
问题详情
登录后处于/profile路径,点击登出按钮后UI已切换为登出状态,但页面仍停留在/profile,未自动跳转到登录页/。
相关代码
Redux 用户切片
export const userSlice = createSlice({ name: "user", initialState: { user: null, }, reducers: { login: ( state, action ) => { state.user = action.payload; }, logout: (state) => { state.user = null; } }, });
App 组件
function App() { const user = useSelector(selectUser); const dispatch = useDispatch(); useEffect(() => { const unsubscribe = auth.onAuthStateChanged((userAuth) => { if (userAuth) { // logged in dispatch(login({ uid: userAuth.uid, email: userAuth.email, })) } else { // logged out dispatch(logout()) } }); return unsubscribe; }, [dispatch]); return ( <div className="app"> <BrowserRouter> {!user ? ( <Routes> <Route path="/" element={<LoginScreen />} /> </Routes> ) : ( <Routes> <Route path="/profile" element={<ProfileScreen/> } /> <Route exact path="/" element={<HomeScreen />} /> </Routes> )} </BrowserRouter> </div> ) }
登出按钮
<button onClick={()=>auth.signOut()} className="profileScreen_SignOut" > Sign Out </button>
原因分析
当前代码仅在Firebase的auth.onAuthStateChanged回调中更新了Redux的用户状态,触发UI切换,但没有处理登出后的页面导航逻辑。浏览器地址停留在/profile,虽然未登录时的路由配置不渲染ProfileScreen,但不会自动跳转。
解决方法
方法1:在状态监听回调中添加跳转
修改App组件,使用useNavigate钩子在登出时主动跳转到登录页,同时添加路由守卫避免未登录访问/profile:
import { BrowserRouter, Routes, Route, useNavigate, Navigate } from 'react-router-dom'; function App() { const user = useSelector(selectUser); const dispatch = useDispatch(); const navigate = useNavigate(); useEffect(() => { const unsubscribe = auth.onAuthStateChanged((userAuth) => { if (userAuth) { dispatch(login({ uid: userAuth.uid, email: userAuth.email, })) } else { dispatch(logout()); navigate('/'); // 登出后立即跳转登录页 } }); return unsubscribe; }, [dispatch, navigate]); return ( <div className="app"> <BrowserRouter> {!user ? ( <Routes> <Route path="/" element={<LoginScreen />} /> {/* 未登录时访问profile直接重定向到登录页 */} <Route path="/profile" element={<Navigate to="/" />} /> </Routes> ) : ( <Routes> <Route path="/profile" element={<ProfileScreen/> } /> <Route exact path="/" element={<HomeScreen />} /> </Routes> )} </BrowserRouter> </div> ) }
方法2:在登出按钮点击事件中处理跳转
直接在登出按钮的回调里,等Firebase登出操作完成后执行跳转:
import { useNavigate } from 'react-router-dom'; function ProfileScreen() { const navigate = useNavigate(); return ( // ...其他组件内容 <button onClick={() => { auth.signOut().then(() => { navigate('/'); }).catch(err => { console.error('登出失败:', err); }); }} className="profileScreen_SignOut" > Sign Out </button> // ...其他组件内容 ) }
内容的提问来源于stack exchange,提问作者Jak
相关产品推荐
相关产品推荐

