1.根据路由信息可知用户的权限控制
//layouts/SecurityLayout.tsximport React from 'react';import { PageLoading } from '@ant-design/pro-layout';import type { ConnectProps } from 'umi';import { Redirect, connect } from 'umi';import { stringify } from 'querystring';import type { ConnectState } from '@/models/connect';import type { CurrentUser } from '@/models/user';type SecurityLayoutProps = { loading?: boolean; currentUser?: CurrentUser;} & ConnectProps;type SecurityLayoutState = { isReady: boolean;};class SecurityLayout extends React.Component<SecurityLayoutProps, SecurityLayoutState> { state: SecurityLayoutState = { isReady: false, }; componentDidMount() { this.setState({ isReady: true, }); const { dispatch } = this.props; if (dispatch) { //获取用户信息,触发model中的方法 dispatch({ type: 'user/fetchCurrent', }); } } render() { const { isReady } = this.state; //从这里可以看出props中获取用户的信息,这里的props是在model中 const { children, loading, currentUser } = this.props; //根据是否登录进行跳转,这里deid是发送请求后获取的数据 const isLogin = currentUser && currentUser.id; const queryString = stringify({ redirect: window.location.href, }); if ((!isLogin && loading) || !isReady) { return <PageLoading />; } if (!isLogin && window.location.pathname !== '/login') { return <Redirect to={`/login?${queryString}`} />; } return children; }}export default connect(({ user, loading }: ConnectState) => ({ currentUser: user.currentUser, loading: loading.models.user,}))(SecurityLayout);
2.在model中获取用户信息
import type { Effect, Reducer } from 'umi';import { queryCurrent, query as queryUsers } from '@/services/user';//定义用户信息的类型export type CurrentUser = { avatar_url?: string; name?: string; title?: string; group?: string; signature?: string; tags?: { key: string; label: string; }[]; userid?: string; unreadCount?: number;};export type UserModelState = { currentUser?: CurrentUser;};//定义redux的类型export type UserModelType = { namespace: 'user'; state: UserModelState; effects: { fetch: Effect; fetchCurrent: Effect; }; reducers: { saveCurrentUser: Reducer<UserModelState>; changeNotifyCount: Reducer<UserModelState>; };};const UserModel: UserModelType = { namespace: 'user', state: { currentUser: {}, }, effects: { *fetch(_, { call, put }) { const response = yield call(queryUsers); yield put({ type: 'save', payload: response, }); }, //判断本地的lacolstorage中是否有数据,如果有,则不需要再次发送请求,如果没有则发送请求并且将请求结果保存到本地缓存中 *fetchCurrent(_, { call, put }) { //查看本地的localstorage是否有用户信息,没有在请求 const userInfo = localStorage.getItem('useInfo'); let response = null; if (!userInfo) { //获取用户信息 response = yield call(queryCurrent); console.log( response); //把用户数据存入缓存 localStorage.setItem('userInfo', JSON.stringify(response)); } else { response = JSON.parse(userInfo); } yield put({ type: 'saveCurrentUser', payload: response, }); }, }, reducers: { saveCurrentUser(state, action) { return { ...state, currentUser: action.payload || {}, }; }, changeNotifyCount( state = { currentUser: {}, }, action, ) { return { ...state, currentUser: { ...state.currentUser, notifyCount: action.payload.totalCount, unreadCount: action.payload.unreadCount, }, }; }, },};export default UserModel;
3.发送请求获取用户信息
//services/user.tsimport request from '@/utils/request';export async function queryCurrent(): Promise<any> { return request('/admin/user');}
4.在登录组件的生命周期中根据缓存中是否有登录信息来判断是否重定向到首页
//page/login/index.tsx useEffect(() => { //判断用户是否登录,如果登录则重定向到首页 const userInfo=localStorage.getItem('userInfo') if(userInfo) history.replace('/') }, [])
5.根据缓存的用户信息去设置首页头部
//src/components/GlobalHeader/AvatarDropdown.tsximport { LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';import { Avatar, Menu, Spin } from 'antd';import React from 'react';import type { ConnectProps } from 'umi';import { history, connect } from 'umi';import type { ConnectState } from '@/models/connect';import type { CurrentUser } from '@/models/user';import HeaderDropdown from '../HeaderDropdown';import styles from './index.less';export type GlobalHeaderRightProps = { currentUser?: CurrentUser; menu?: boolean;} & Partial<ConnectProps>;class AvatarDropdown extends React.Component<GlobalHeaderRightProps> { onMenuClick = (event: { key: React.Key; keyPath: React.Key[]; item: React.ReactInstance; domEvent: React.MouseEvent<HTMLElement>; }) => { const { key } = event; if (key === 'logout') { const { dispatch } = this.props; if (dispatch) { dispatch({ type: 'login/logout', }); } return; } history.push(`/account/${key}`); }; render(): React.ReactNode { const { currentUser = { avatar_url: '', name: '', }, menu, } = this.props; const menuHeaderDropdown = ( <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}> {menu && ( <Menu.Item key="center"> <UserOutlined /> 个人中心 </Menu.Item> )} {menu && ( <Menu.Item key="settings"> <SettingOutlined /> 个人设置 </Menu.Item> )} {menu && <Menu.Divider />} <Menu.Item key="logout"> <LogoutOutlined /> 退出登录 </Menu.Item> </Menu> ); return currentUser && currentUser.name ? ( // 这里是设置头部 <HeaderDropdown overlay={menuHeaderDropdown}> <span className={`${styles.action} ${styles.account}`}> <Avatar size="small" className={styles.avatar} src={currentUser.avatar_url} alt="avatar" /> <span className={`${styles.name} anticon`}>{currentUser.name}</span> </span> </HeaderDropdown> ) : ( <span className={`${styles.action} ${styles.account}`}> <Spin size="small" style={{ marginLeft: 8, marginRight: 8, }} /> </span> ); }}export default connect(({ user }: ConnectState) => ({ currentUser: user.currentUser,}))(AvatarDropdown);