react简单2步,封装鉴权路由

249 阅读1分钟

1.新建 src/components/AuthRoute 文件夹

2.在里面新建index.tsx

//这里用了自己封装的 history 配合下面的回跳页面。详情可以看我的 封装history的文章
import history from '@/utils/history'

//自己封装的获取token的函数,各位可以自己处理逻辑
import { hasToken } from "@//utils/storage";
import { message } from "antd";
import React from "react";
import { Redirect, Route } from "react-router-dom";

//把标签里面的属性全部接收,并且传给 Route 组件
type AtahType = {
  path: string;
  component: React.FC;
  [x: string]: any;
};

export default function AuthRoute({ path, component: Com, ...rest }: AtahType) {
  return (
    <Route
      path={path}
      {...rest}
      render={() => {
        if (hasToken()) return <Com />;
        else {
          message.warning("登录失效!");
          return (
            <Redirect
              to={{
                pathname: "/login",
                //可以自己定义信息比如登录之后会跳到上个页面
                state: { from: history.location.pathname }
              }}
            />
          );
        }
      }}
    />
  );
}

3.使用

      {/* 关于路由 */}
      <Router>
        
          <Switch>
              //普通路由,没有鉴权功能
            <Route path="/login" component={Login} />
              //鉴权路由
            <AuthRoute path="/" component={Layout} />
          </Switch>
        
      </Router>