From d4ea72e2071fd27832307811391469dd70772217 Mon Sep 17 00:00:00 2001 From: zdl <3489966805@qq.com> Date: Mon, 13 Oct 2025 16:40:06 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=A7=A3=E5=86=B3=E6=9D=83=E9=99=90?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C=E9=98=BB=E5=A1=9E=E9=A1=B5=E9=9D=A2=E6=B8=B2?= =?UTF-8?q?=E6=9F=93=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/contexts/AuthContext.js | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/contexts/AuthContext.js b/src/contexts/AuthContext.js index ebf0f7ea..1c19af65 100755 --- a/src/contexts/AuthContext.js +++ b/src/contexts/AuthContext.js @@ -22,7 +22,7 @@ export const useAuth = () => { // 认证提供者组件 export const AuthProvider = ({ children }) => { const [user, setUser] = useState(null); - const [isLoading, setIsLoading] = useState(true); + const [isLoading, setIsLoading] = useState(false); // ⚡ 改为 false,不阻塞首屏渲染 const [isAuthenticated, setIsAuthenticated] = useState(false); const navigate = useNavigate(); const toast = useToast(); @@ -32,14 +32,21 @@ export const AuthProvider = ({ children }) => { try { console.log('🔍 检查Session状态...'); + // 创建超时控制器 + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 5000); // 5秒超时 + const response = await fetch(`${API_BASE_URL}/api/auth/session`, { method: 'GET', credentials: 'include', // 重要:包含cookie headers: { 'Content-Type': 'application/json', - } + }, + signal: controller.signal // 添加超时信号 }); + clearTimeout(timeoutId); + if (!response.ok) { throw new Error('Session检查失败'); } @@ -56,16 +63,17 @@ export const AuthProvider = ({ children }) => { } } catch (error) { console.error('❌ Session检查错误:', error); + // 网络错误或超时,设置为未登录状态 setUser(null); setIsAuthenticated(false); - } finally { - setIsLoading(false); } + // ⚡ 移除 finally 中的 setIsLoading(false),不再阻塞渲染 }; - // 初始化时检查Session + // ⚡ 初始化时检查Session - 并行执行,不阻塞页面渲染 useEffect(() => { - checkSession(); + checkSession(); // 直接调用,与页面渲染并行 + // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // 监听路由变化,检查session(处理微信登录回调) @@ -79,6 +87,7 @@ export const AuthProvider = ({ children }) => { window.addEventListener('popstate', handleRouteChange); return () => window.removeEventListener('popstate', handleRouteChange); + // eslint-disable-next-line react-hooks/exhaustive-deps }, [isAuthenticated]); // 更新本地用户的便捷方法