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