相比于vue的路由 react的路由就没有那么好用了
基本上需要登录的项目都需要做路由拦截功能
下面一起来看看react中是怎么实现路由拦截的
APP.js
import React from "react";
import {BrowserRouter as Router, Switch} from 'react-router-dom';
import "./App.css";
// 路由部分 自行拆文件去
import FrontendAuth from './router/FrontendAuth'
import Home from './home/index'
import Login from "./login/index";
import NotFund from "./notFund"
const routes = [
{ path: '/', meta: { title: '首页' }, component: Home, auth: true },
{ path: '/login', meta: { title: '登录' }, component: Login, auth: false },
{ path: '/app', meta: { title: '首页' }, component: Home, auth: true },
{ path: '/404', meta: { title: '404' }, component: NotFund }
]
// 路由部分结束
class App extends React.Component {
render() {
return (
<Router>
<Switch>
<FrontendAuth routerConfig={routes}></FrontendAuth>
</Switch>
</Router>
);
}
}
export default App;
相比于之前 我们封装了一个FrontendAuth组件
FrontendAuth.js
import React from 'react'
import { Route, Redirect } from "react-router-dom";
export default class FrontendAuth extends React.Component {
constructor (props) {
super (props)
}
render () {
const { routerConfig, location } = this.props
const { pathname } = location
const isLogin = sessionStorage.getItem('username')
console.log(routerConfig, pathname)
const currentPath = routerConfig.find(item => item.path === pathname)
if (currentPath && !currentPath.auth && !isLogin) {
return (<Route exact path={pathname} component={currentPath.component}></Route>)
}
if (isLogin) {
if (pathname === '/login') {
// 如果是登陆状态,想要跳转到登陆,重定向到主页
return (<Redirect to="/app"></Redirect>)
} else {
if (currentPath) {
// 如果路由合法,就跳转到相应的路由
return (<Route exact path={pathname} component={currentPath.component}></Route>)
} else {
// 如果路由不合法,重定向到 404 页面
return(<Redirect to="/404"/>)
}
}
} else {
// 非登陆状态下,当路由合法时且需要权限校验时,跳转到登陆页面,要求登陆
if (currentPath && currentPath.auth) {
return <Redirect to="/login" />;
} else {
// 非登陆状态下,路由不合法时,重定向至 404
return <Redirect to="/404" />;
}
}
}
}
这样一个简单的路由拦截功能就实现啦