feat: 解决权限校验阻塞页面渲染问题

This commit is contained in:
zdl
2025-10-13 16:40:06 +08:00
parent fae8ef10b1
commit d4ea72e207

View File

@@ -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]);
// 更新本地用户的便捷方法