fix(admin-web): 修复 AdminLayout 渲染期间调用 router.replace 导致 React #310 错误

将未登录跳转逻辑从 render 函数移至 useEffect,
避免在渲染子组件时触发父组件状态更新。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
hailin 2026-03-04 05:43:58 -08:00
parent 91f06890a5
commit 7aea49a0c9
1 changed files with 10 additions and 8 deletions

View File

@ -1,6 +1,6 @@
'use client';
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import Link from 'next/link';
import { t } from '@/i18n/locales';
@ -100,13 +100,15 @@ export const AdminLayout: React.FC<{ children: React.ReactNode }> = ({ children
const { isAuthenticated, isLoading, user, logout } = useAuth();
const [collapsed, setCollapsed] = useState(false);
// 未登录 → /login
if (!isLoading && !isAuthenticated) {
router.replace('/login');
return null;
}
// 加载中显示空白
if (isLoading) return null;
// 未登录 → /login必须在 useEffect 中跳转,不能在 render 期间调用 router
useEffect(() => {
if (!isLoading && !isAuthenticated) {
router.replace('/login');
}
}, [isLoading, isAuthenticated, router]);
// 加载中或未登录时显示空白
if (isLoading || !isAuthenticated) return null;
// Derive activeKey from current pathname
const activeKey = pathname.replace(/^\//, '') || 'dashboard';