Authentication状态异常:登出后私有路由仍可访问求助
问题分析与解决方案
问题根源
- 组件未响应sessionStorage变化:
PrivateRoutes直接从sessionStorage取值,但sessionStorage更新时组件不会自动重新渲染,导致登出后仍显示私有路由内容。 - Zustand状态未同步:当前Zustand store仅在初始化时读取
sessionStorage,后续sessionStorage变化不会同步到store,且私有路由未使用store状态做判断。 - 状态更新不一致:登录、登出操作仅修改
sessionStorage,未更新Zustand状态,导致两处状态脱节。
分步解决方案
1. 修复Zustand Store,实现状态与sessionStorage同步
修改Store.js,添加状态更新方法,确保状态变化时同步更新sessionStorage:
import { create } from 'zustand'; const useStore = create((set) => ({ // sessionStorage存的是字符串,需转为布尔值 authenticated: sessionStorage.getItem("authenticated") === "true" || false, // 添加更新状态的方法 setAuthenticated: (value) => { sessionStorage.setItem("authenticated", value.toString()); set({ authenticated: value }); } })); export default useStore;
2. 登录时通过Store更新状态
修改FetchAuthentication.js,调用store方法更新认证状态:
import jwtDecode from "jwt-decode"; import useStore from './Store'; const handleAuthentication = (result) => { let decodedJWT = jwtDecode(result); console.log(decodedJWT); // 通过store更新认证状态 useStore.getState().setAuthenticated(true); } const FetchAuthentication = (email, password) => { var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json"); var raw = JSON.stringify({ "email": email, "password": password }); var requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: 'follow' }; fetch("xxxxxxxxxxxxxxxxxxx", requestOptions) .then(response => response.text()) .then(result => handleAuthentication(result)) .catch(error => console.log('error', error)); }; export { FetchAuthentication };
3. 私有路由使用Zustand状态做判断
修改PrivateRoutes.js,从store获取认证状态,确保状态变化时组件重新渲染:
import { Outlet, Navigate } from "react-router-dom"; import useStore from './Store'; const PrivateRoutes = () => { const authenticated = useStore(state => state.authenticated); console.log(authenticated); // 建议跳转到具体错误页面,而非通配符路径 return authenticated ? <Outlet /> : <Navigate to="/error" />; }; export default PrivateRoutes;
4. 登出时通过Store更新状态
修改Navbar的登出方法,调用store方法更新状态:
import useStore from './Store'; const handleLogout = () => { useStore.getState().setAuthenticated(false); setSelectedProjectIndex(0); };
关键注意事项
sessionStorage存储的所有值都是字符串,直接判断会导致"false"被视为true,必须转为布尔值后再使用。- 所有修改认证状态的操作必须通过Zustand的
setAuthenticated方法,确保store与sessionStorage状态一致,同时触发组件重新渲染。
内容的提问来源于stack exchange,提问作者Noam TheLoreFnatic Hadad
相关产品推荐
相关产品推荐

