判断用户是否登录,从而进行路由的重定向。
- 创建文件 “./component/AuthRoute/index.js”
- 导入
import React, {useContext, createContext, useState} from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link,
//Redirect重定向组件
Redirect,
useHistory,
useLocation
} from "react-router-dom";
//isAuth为判断Token是否存在,即判断用户是否登录
import {isAuth,} from "../../utils/auth"
- 封装重定向组件
const AuthRoute = ({component: Component, ...res}) => {
return <Route
{...res}
render={props => {
const isLoging = isAuth();
if (isLoging) {
//已经登录
return <Component {...props}/>
} else {
//未登录
return <Redirect to={{
pathname: "/login",
state: {
form: props.location,
}
}}/>
}
}}/>
}
- 使用
在app.js文件中导入
//导入路由重定向
import AuthRoute from “./component/AuthRoute”;
将需要进行判断用户是否登录才能展示的路由进行替换
<Route path="/map" component={MyMap}/>
//替换
<AuthRoute path="/map" component={MyMap}/>
即可实现未登录重定向到登录页面