| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- import { useEffect, useRef } from 'react';
- import { useNavigate } from 'react-router-dom';
- import { getNextUnvisitedRoute, hasUserId, getUserLevel, getStorage, STORAGE_KEYS } from '@/utils/storage';
- /**
- * 根路由重定向组件
- * 根据访问历史自动跳转到合适的页面
- * 不再在这里创建用户,只做路由分发
- */
- export const RootRedirect = () => {
- const navigate = useNavigate();
- const hasRunRef = useRef(false); // 防止在 React.StrictMode 下重复执行
- useEffect(() => {
- // 在开发环境的 React.StrictMode 下,useEffect 会执行两次
- // 这里用 ref 保证整个重定向逻辑只跑一次,避免重复创建用户请求
- if (hasRunRef.current) {
- return;
- }
- hasRunRef.current = true;
- const handleRedirect = () => {
- console.log('[RootRedirect] 开始处理重定向(仅根据路由状态跳转,不创建用户)...');
- // 如果本地没有 userId,默认进入 welcome
- if (!hasUserId()) {
- console.log('[RootRedirect] 本地无 user_id,跳转到 /welcome');
- navigate('/welcome', { replace: true });
- return;
- }
- // 检查用户等级和登录状态:如果用户等级 >= 5 且未登录,跳转到 level5-welcome
- const userLevel = getUserLevel();
- const isLoggedIn = getStorage(STORAGE_KEYS.IS_LOGGED_IN) === 'true';
- if (!isLoggedIn && userLevel >= 5) {
- console.log('[RootRedirect] 用户等级 >= 5 且未登录,跳转到 /level5-welcome');
- navigate('/level5-welcome', { replace: true });
- return;
- }
- // 获取下一个未访问的路由
- const nextRoute = getNextUnvisitedRoute();
- console.log('[RootRedirect] 下一个路由:', nextRoute);
-
- if (nextRoute) {
- // 有未访问的路由,跳转到下一个
- navigate(nextRoute, { replace: true });
- } else {
- // 所有路由都访问过了,跳转到聊天页(最后一个路由)
- navigate('/chatbot', { replace: true });
- }
- };
- handleRedirect();
- }, [navigate]);
- // 显示加载状态
- return (
- <div className="w-full h-full flex items-center justify-center bg-white overflow-hidden">
- <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
- </div>
- );
- };
|