Ant design pro使用(五):未登录时自动跳转到登录页,登录之后不再返回登录页

判断是否登录,要在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组件中进行逻辑判断

  1. 在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',
  //     });
  //   }
  // }, []);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值