From c2497ec4330773089116a6ed830793a201741ae1 Mon Sep 17 00:00:00 2001 From: wong <106998207@qq.com> Date: Fri, 23 May 2025 16:47:37 +0800 Subject: [PATCH] =?UTF-8?q?=E3=80=90=E6=93=8D=E7=9B=98=E6=89=8B=E3=80=91?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E9=80=80=E5=87=BA=E7=99=BB=E5=BD=95=E5=8F=8D?= =?UTF-8?q?=E5=A4=8D=E8=B7=B3=E8=BD=AC=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cunkebao/app/components/AuthProvider.tsx | 10 +++++++--- Cunkebao/app/login/page.tsx | 15 ++++++++++++--- Cunkebao/lib/api.ts | 16 +++++++--------- 3 files changed, 26 insertions(+), 15 deletions(-) diff --git a/Cunkebao/app/components/AuthProvider.tsx b/Cunkebao/app/components/AuthProvider.tsx index c0291fd8..8f5877ad 100644 --- a/Cunkebao/app/components/AuthProvider.tsx +++ b/Cunkebao/app/components/AuthProvider.tsx @@ -147,6 +147,7 @@ export function AuthProvider({ children }: AuthProviderProps) { }, []) // 空依赖数组,仅在组件挂载时执行一次 const handleLogout = () => { + // 先清除所有认证相关的状态 safeLocalStorage.removeItem("token") safeLocalStorage.removeItem("token_expired") safeLocalStorage.removeItem("s2_accountId") @@ -155,11 +156,16 @@ export function AuthProvider({ children }: AuthProviderProps) { setToken(null) setUser(null) setIsAuthenticated(false) + + // 使用 window.location 而不是 router.push,避免状态更新和路由跳转的竞态条件 + if (typeof window !== 'undefined') { + window.location.href = '/login' + } } const login = (newToken: string, userData: User) => { safeLocalStorage.setItem("token", newToken) - safeLocalStorage.setItem("user", JSON.stringify(userData)) + safeLocalStorage.setItem("userInfo", JSON.stringify(userData)) setToken(newToken) setUser(userData) setIsAuthenticated(true) @@ -167,8 +173,6 @@ export function AuthProvider({ children }: AuthProviderProps) { const logout = () => { handleLogout() - // 登出后不强制跳转到登录页 - // router.push("/login") } // 用于刷新 token 的方法 diff --git a/Cunkebao/app/login/page.tsx b/Cunkebao/app/login/page.tsx index 37c93913..f12e423f 100644 --- a/Cunkebao/app/login/page.tsx +++ b/Cunkebao/app/login/page.tsx @@ -155,10 +155,19 @@ export default function LoginPage() { useEffect(() => { // 检查是否已登录,如果已登录且不在登录页面,则跳转到首页 - if (isAuthenticated && window.location.pathname === '/login') { - router.push("/") + if (isAuthenticated) { + // 获取重定向URL + const params = new URLSearchParams(window.location.search) + const returnUrl = params.get('returnUrl') + + // 如果有重定向URL,则跳转到该URL,否则跳转到首页 + if (returnUrl) { + window.location.href = decodeURIComponent(returnUrl) + } else { + window.location.href = "/" + } } - }, [isAuthenticated, router]) + }, [isAuthenticated]) return (