Ant design pro使用(五):未登入時自動跳轉到登入頁,登入之後不再返回登入頁

qq_32496215發表於2020-11-09

判斷是否登入,要在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',
  //     });
  //   }
  // }, []);

相關文章