@@ -42,34 +42,48 @@ interface UserData {
4242 role ?: string ;
4343}
4444
45+ interface AuthState {
46+ isLoggedIn : boolean ;
47+ userData : UserData | null ;
48+ }
49+
50+ // 从 localStorage 读取认证状态
51+ function getAuthState ( ) : AuthState {
52+ if ( typeof window === 'undefined' ) {
53+ return { isLoggedIn : false , userData : null } ;
54+ }
55+
56+ const token = localStorage . getItem ( 'token' ) ;
57+ const user = localStorage . getItem ( 'user' ) ;
58+
59+ if ( token && user ) {
60+ try {
61+ return { isLoggedIn : true , userData : JSON . parse ( user ) } ;
62+ } catch {
63+ return { isLoggedIn : false , userData : null } ;
64+ }
65+ }
66+
67+ return { isLoggedIn : false , userData : null } ;
68+ }
69+
4570export default function Header ( ) {
4671 const pathname = usePathname ( ) ;
47- const [ isLoggedIn , setIsLoggedIn ] = useState ( false ) ;
48- const [ userData , setUserData ] = useState < UserData | null > ( null ) ;
72+ const [ authState , setAuthState ] = useState < AuthState > ( { isLoggedIn : false , userData : null } ) ;
4973
5074 useEffect ( ( ) => {
51- // 检查用户是否已登录
52- const token = localStorage . getItem ( 'token' ) ;
53- const user = localStorage . getItem ( 'user' ) ;
54-
55- if ( token && user ) {
56- setIsLoggedIn ( true ) ;
57- try {
58- setUserData ( JSON . parse ( user ) ) ;
59- } catch ( e ) {
60- console . error ( '解析用户数据失败' , e ) ;
61- }
62- }
75+ setAuthState ( getAuthState ( ) ) ;
6376 } , [ ] ) ;
6477
6578 const handleLogout = ( ) => {
6679 localStorage . removeItem ( 'token' ) ;
6780 localStorage . removeItem ( 'user' ) ;
68- setIsLoggedIn ( false ) ;
69- setUserData ( null ) ;
81+ setAuthState ( { isLoggedIn : false , userData : null } ) ;
7082 window . location . href = '/' ;
7183 } ;
7284
85+ const { isLoggedIn, userData } = authState ;
86+
7387 return (
7488 < ScrollHeader >
7589 < div className = "navbar container mx-auto px-4 h-16" >
0 commit comments