fix: 修复登录后左侧菜单不显示问题

This commit is contained in:
2025-06-17 10:00:04 +08:00
parent 8520e19309
commit 1d92ed0749
9 changed files with 133 additions and 75 deletions
+43 -36
View File
@@ -95,50 +95,56 @@ export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) =
userId: initialState?.currentUser?.userId,
},
request: async () => {
// initialState.currentUser 中包含了所有用户信息
const menuData = await fetchMenuData();
try {
// initialState.currentUser 中包含了所有用户信息
const menuData = await fetchMenuData();
const mapIcon = (css: string | undefined) => {
switch (css) {
case 'layui-icon-set':
return <SettingOutlined />;
case 'layui-icon-friends':
return <UserOutlined />;
case 'layui-icon-user':
return <TeamOutlined />;
case 'layui-icon-menu-fill':
return <MenuOutlined />;
default:
return <AppstoreOutlined />;
}
};
const mapIcon = (css: string | undefined) => {
switch (css) {
case 'layui-icon-set':
return <SettingOutlined />;
case 'layui-icon-friends':
return <UserOutlined />;
case 'layui-icon-user':
return <TeamOutlined />;
case 'layui-icon-menu-fill':
return <MenuOutlined />;
default:
return <AppstoreOutlined />;
}
};
const mapMenu = (value: API.Menu[]): MenuDataItem[] => {
return value.map((item) => {
return {
key: item.id + '',
name: item.name,
locale: false,
path:
item.path?.endsWith('.html') || item.path?.startsWith('http')
? item.path
: undefined,
icon: mapIcon(item.css),
children: item.subMenus && mapMenu(item.subMenus),
};
});
};
const menus = mapMenu(menuData);
return [
{ key: 'welcome', name: ' 首页', path: '/welcome', icon: <CrownOutlined /> },
...menus,
];
const mapMenu = (value: API.Menu[]): MenuDataItem[] => {
return value.map((item) => {
return {
key: item.id + '',
name: item.name,
locale: false,
path:
item.path?.endsWith('.html') || item.path?.startsWith('http')
? item.path
: undefined,
icon: mapIcon(item.css),
children: item.subMenus && mapMenu(item.subMenus),
};
});
};
const menus = mapMenu(menuData);
return [
{ key: 'welcome', name: '首页', path: '/welcome', icon: <CrownOutlined /> },
...menus,
];
} catch (error) {
console.error('获取菜单数据失败:', error);
return [];
}
},
},
headerContentRender: () => {
return (
<Space>
<Divider type="vertical" />
{/* 注释掉相关链接下拉菜单
<Dropdown
placement="top"
overlay={
@@ -235,6 +241,7 @@ export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) =
</Space>
</a>
</Dropdown>
*/}
</Space>
);
},
@@ -47,6 +47,7 @@ const GlobalHeaderRight: React.FC = () => {
console.log('input', value);
}}
/> */}
{/* 注释掉帮助链接
<span
className={styles.action}
onClick={() => {
@@ -55,6 +56,8 @@ const GlobalHeaderRight: React.FC = () => {
>
<QuestionCircleOutlined />
</span>
*/}
{/* 注释掉GitHub链接
<span
className={styles.action}
onClick={() => {
@@ -63,6 +66,7 @@ const GlobalHeaderRight: React.FC = () => {
>
<GithubOutlined />
</span>
*/}
<span
className={styles.action}
onClick={() => history.push('/message')}
@@ -1,5 +1,5 @@
export default {
'menu.welcome': '欢迎',
'menu.welcome': '首页',
'menu.more-blocks': '更多区块',
'menu.home': '首页',
'menu.admin': '管理页',
@@ -1,10 +1,18 @@
import { useState, useEffect } from 'react';
import { getMessages } from '@/services/message/api';
import { useModel } from 'umi';
export default () => {
const [unreadCount, setUnreadCount] = useState<number>(0);
const { initialState } = useModel('@@initialState');
const fetchUnreadCount = async () => {
// 如果未登录,不请求站内信
if (!initialState?.currentUser) {
setUnreadCount(0);
return;
}
try {
const response = await getMessages({ status: 0, pageSize: 1 });
setUnreadCount(response.total || 0);
@@ -18,7 +26,7 @@ export default () => {
// 设置定时刷新
const timer = setInterval(fetchUnreadCount, 60000); // 每分钟刷新一次
return () => clearInterval(timer);
}, []);
}, [initialState?.currentUser]); // 添加currentUser作为依赖,当登录状态改变时重新获取
return {
unreadCount,
@@ -2,6 +2,10 @@
@import '~antd/es/style/themes/default.less';
.container {
padding: 24px;
background: #f0f2f5;
min-height: calc(100vh - 48px);
:global {
.ant-card {
border-radius: 8px;
@@ -16,7 +20,8 @@
}
.statCard {
height: 180px;
height: auto;
min-height: 180px;
.statHeader {
display: flex;
@@ -35,10 +40,13 @@
display: flex;
justify-content: space-between;
align-items: flex-end;
flex-wrap: wrap;
gap: 16px;
:global {
.ant-statistic {
flex: 1;
min-width: 120px;
}
.ant-progress {
@@ -77,11 +85,11 @@
}
.chartsRow {
margin-top: 16px;
margin-top: 24px;
}
.businessRow {
margin-top: 16px;
margin-top: 24px;
}
.rankList {
@@ -127,13 +135,24 @@
// 响应式调整
@media screen and (max-width: 768px) {
.container {
padding: 16px;
}
.statCard {
height: auto;
margin-bottom: 16px;
}
.chartsRow, .businessRow {
margin-top: 8px;
margin-top: 16px;
}
.subStats {
:global {
.ant-statistic {
min-width: 100px;
}
}
}
}
@@ -198,10 +217,6 @@
.ant-card-body {
padding: 24px;
}
.ant-empty {
padding: 32px 0;
}
}
}
@@ -89,7 +89,7 @@ const Welcome: React.FC = () => {
smooth: true,
animation: true,
legend: {
position: 'top',
position: 'top' as const,
},
areaStyle: {
fillOpacity: 0.6,
@@ -114,7 +114,7 @@ const Welcome: React.FC = () => {
xField: 'type',
yField: 'value',
label: {
position: 'middle',
position: 'middle' as const,
style: {
fill: '#FFFFFF',
opacity: 0.6,
@@ -219,12 +219,12 @@ const Welcome: React.FC = () => {
{/* 图表展示 */}
<Row gutter={[16, 16]} className={styles.chartsRow}>
<Col xs={24} md={16}>
<Col xs={24} lg={16}>
<Card title="订单趋势" loading={loading}>
<Area {...orderTrendConfig} height={300} />
</Card>
</Col>
<Col xs={24} md={8}>
<Col xs={24} lg={8}>
<Card title="设备分布" loading={loading}>
<Pie {...deviceDistConfig} height={300} />
</Card>
@@ -233,17 +233,17 @@ const Welcome: React.FC = () => {
{/* 业务数据 */}
<Row gutter={[16, 16]} className={styles.businessRow}>
<Col xs={24} md={12}>
<Card title="收入构成" loading={loading}>
<Column {...incomeConfig} height={250} />
<Col xs={24} lg={12}>
<Card title="收入统计" loading={loading}>
<Column {...incomeConfig} height={300} />
</Card>
</Col>
<Col xs={24} md={12}>
<Card title="景区排行" loading={loading}>
<Col xs={24} lg={12}>
<Card title="景区排名" loading={loading}>
<div className={styles.rankList}>
{(statistics.tourismRanking || []).map((item: any, index: number) => (
{statistics.tourismRanking?.map((item: { id: string; name: string; value: number }, index: number) => (
<div key={item.id} className={styles.rankItem}>
<span className={`${styles.rankNum} ${index < 3 ? styles.topThree : ''}`}>
<span className={`${styles.rankNum} ${index < 3 ? 'topThree' : ''}`}>
{index + 1}
</span>
<span className={styles.rankName}>{item.name}</span>
@@ -3,7 +3,7 @@ import { login } from '@/services/login/api';
import { InfoCircleOutlined, LockOutlined, UserOutlined, AppstoreOutlined } from '@ant-design/icons';
import { LoginForm, ProFormCaptcha, ProFormText, ProFormCheckbox } from '@ant-design/pro-components';
import { message, Tooltip, Spin, Form } from 'antd';
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useRef } from 'react';
import { FormattedMessage, history, useIntl, useModel } from 'umi';
import { v4 as uuidv4 } from 'uuid';
import styles from './index.less';
@@ -14,18 +14,27 @@ const Login: React.FC = () => {
const { initialState, setInitialState } = useModel('@@initialState');
const intl = useIntl();
const [form] = Form.useForm();
const mountedRef = useRef(true);
useEffect(() => {
return () => {
mountedRef.current = false;
};
}, []);
const fetchUserInfo = async () => {
try {
const userInfo = await initialState?.fetchUserInfo?.();
if (userInfo) {
if (userInfo && mountedRef.current) {
await setInitialState((s) => ({
...s,
currentUser: userInfo,
}));
}
} catch (error) {
message.error('获取用户信息失败');
if (mountedRef.current) {
message.error('获取用户信息失败');
}
}
};
@@ -42,7 +51,7 @@ const Login: React.FC = () => {
// 自动填充缓存的租户标识
useEffect(() => {
const clientId = getCachedTenantId();
if (clientId) {
if (clientId && mountedRef.current) {
form.setFieldsValue({
clientId,
});
@@ -51,27 +60,36 @@ const Login: React.FC = () => {
const handleSubmit = async (values: API.LoginParams) => {
try {
if (!mountedRef.current) return;
setLoading(true);
const msg = await login({ ...values, deviceId: uuid });
debugger;
if (msg.resp_code === 0 && msg.data?.access_token) {
sessionStorage.setItem('access_token', msg.data.access_token);
message.success('登录成功!');
await fetchUserInfo();
const { query } = history.location;
const { redirect } = query as { redirect: string };
history.push(redirect || '/');
return;
if (mountedRef.current) {
message.success('登录成功!');
await fetchUserInfo();
await initialState?.fetchUserInfo?.();
const { query } = history.location;
const { redirect } = query as { redirect: string };
history.push(redirect || '/');
return;
}
}
message.error(msg.resp_msg || '登录失败');
setUuid(uuidv4());
if (mountedRef.current) {
message.error(msg.resp_msg || '登录失败');
setUuid(uuidv4());
}
} catch (error) {
message.error('登录失败,请重试!');
if (mountedRef.current) {
message.error('登录失败,请重试!');
}
} finally {
setLoading(false);
if (mountedRef.current) {
setLoading(false);
}
}
};
@@ -151,6 +169,10 @@ const Login: React.FC = () => {
onClick={() => setUuid(uuidv4())}
/>
)}
onGetCaptcha={async () => {
// 由于我们使用的是图片验证码,这里不需要实现
return Promise.resolve();
}}
rules={[
{
required: true,
@@ -6,12 +6,14 @@ declare namespace API {
resp_code?: number;
resp_msg?: number;
datas?: T[];
data?: T;
};
type OptionalResult<T> = {
resp_code?: number;
resp_msg?: number;
datas?: T;
data?: T;
};
type CurrentUser = SYSTEM.User & {
@@ -3,7 +3,7 @@ import { request } from 'umi';
/** 获取消息列表 */
export async function getMessages(params: any) {
const { current, pageSize, ...restParams } = params;
return request<API.Response<MESSAGE.Message[]>>('/api-order/messages', {
return request<API.Response<{ data: MESSAGE.Message[]; total: number }>>('/api-order/messages', {
method: 'GET',
params: {
page: params.page || 1,