与vue不同,vue直接使用beforeEach即可实现全局路由守卫等功能。

react要实现路由守卫得自己配置。

实现该功能的前提是你需要先掌握react的高阶组件的使用

需要配置一张路由表。

需要使用高阶组件。

路由表格式

import Home from '需要展示的页面'

var routes = [

{path: "/", name: "home", component: Home, auth: true}

]

// auth 是否需要登录

export default routes ;

高阶组件的实现

import React, { Component } from "react";

import { Route, Redirect } from "react-router-dom";

class FrontendAuth extends Component {

render() {

const { routerConfig, location } = this.props;

const { pathname } = location;

const isLogin = sessionStorage.getItem("token");

// console.log(pathname)

// console.log(routerConfig);

// 如果该路由不用进行权限校验,登录状态下登陆页除外

// 因为登陆后,无法跳转到登陆页

// 这部分代码,是为了在非登陆状态下,访问不需要权限校验的路由

const targetRouterConfig = routerConfig.find(

(item) => {

return item.path.replace(/\s*/g,"") === pathname

}

);

if (targetRouterConfig && !targetRouterConfig.auth && !isLogin) {

const { component } = targetRouterConfig;

return

}

if (isLogin) {

// 如果是登陆状态,想要跳转到登陆,重定向到主页

if (pathname === "/login") {

return ;

} else {

// 如果路由合法,就跳转到相应的路由

if (targetRouterConfig) {

return ();

} else {

// 如果路由不合法,重定向到 404 页面

return ;

}

}

} else {

// 非登陆状态下,当路由合法时且需要权限校验时,跳转到登陆页面,要求登陆

if (targetRouterConfig && targetRouterConfig.auth) {

console.log('跳转登录登录')

return ;

} else {

// 非登陆状态下,路由不合法时,重定向至 404

return ;

}

}

}

}

export default FrontendAuth

使用高阶组件

import React from 'react';

import {Switch, BrowserRouter} from 'react-router-dom'

// 你的高阶组件

import FrontendAuth from './FrontendAuth'

// 你的路由表

import {routerObj} from '../views/index'

function router() {

return (

);

}

export default router;

后续会更新如何自动化配置路由表,以及在路由中如何自定义懒加载和预加载页面和组件

(最近在用react重新开发博客-。-有空在更)

Logo

前往低代码交流专区

更多推荐