判断是否登录,要在routes中配置 SecurityLayout
config/config.ts
routes:[
{
path:'/user',
layout: false,
routes:[
{path:'/user',redirect:'/user/login'},
{
path:'/user/login',
name:'登录',
component:'./User/Login'
},
{
path:'/user/design',
name:'注册',
component:'./User/Design'
},
{
path:'/user/forget',
name:'忘记密码',
component:'./User/Forget'
},
{
component:'./Empty'
}
]
},
{
path:'/',
component: '../layouts/SecurityLayout', //******关键在这里
routes:[
{
path:'/',
component:'../layouts/BasicLayout',
// authority:['admin','user'],//设置权限
routes:[
{path:'/',redirect:'/equipment/mall'},
{
path:'/equipment',
name:'设备管理',
icon:'videoCamera',
routes:[
{path:'equipment/mall',name:'设备商城',component:'./Equipment/Mall'},
{path:'/equipment/cpe',name:'CPE设备列表',component: './Equipment/Cpe'},
{path:'/equipment/camera',name:'摄像头列表',component:'./Equipment/Camera'}
]
},
{path:'/repair',name:'设备报修',icon:'tool',component:'./Repair'},
{path:'/test',name:'测试模块',icon:'tool',component:'./Test'},
]
}
]
},
]
在SecurityLayout组件中进行逻辑判断
- 在componentDidMount()中
import {getSeesion,getUserId} from '@/utils/memory'
componentDidMount(){
this.setState({
isReady:true
})
if(getSeesion() && getUserId()){
//如果session 和 id存在,
const {dispatch} = this.props;
dispatch({type: 'user/fetchCurrent'});//调用接口,获取用户信息
}
}
2.在render中进行逻辑判断修改
render() {
const { isReady } = this.state;
const { children, loading } = this.props;
// You can replace it to your authentication rule (such as check token exists)
// 你可以把它替换成你自己的登录认证规则(比如判断 token 是否存在)
const isLogin = getSession() && getUserID();
const queryString = stringify({
redirect: window.location.href,
});
if ((!isLogin && loading) || !isReady) {
return <PageLoading />;
}
if (!isLogin && window.location.pathname !== '/user/login') {
return <Redirect to={`/user/login?${queryString}`} />;
}
return children;
}
3.BasicLayout中将发送获取接口的事件注释,不然会调用2次
BasicLayout要注释的地方
// useEffect(() => {
// console.log('101')
// if (dispatch) {
// dispatch({
// type: 'user/fetchCurrent',
// });
// }
// }, []);