react实现路由守卫

朴灿烈づ我的快乐病毒、 2021-09-10 04:52 848阅读 0赞

vue不同,vue直接使用beforeEach即可实现全局路由守卫等功能。
react要实现路由守卫得自己配置。
实现该功能的前提是你需要先掌握react的高阶组件的使用

  1. 需要配置一张路由表。
  2. 需要使用高阶组件。

路由表格式

  1. import Home from '需要展示的页面'
  2. var routes = [
  3. {path: "/", name: "home", component: Home, auth: true}
  4. ]
  5. // auth 是否需要登录
  6. export default routes ;

高阶组件的实现

  1. import React, { Component } from "react";
  2. import { Route, Redirect } from "react-router-dom";
  3. class FrontendAuth extends Component {
  4. render() {
  5. const { routerConfig, location } = this.props;
  6. const { pathname } = location;
  7. const isLogin = sessionStorage.getItem("token");
  8. // console.log(pathname)
  9. // console.log(routerConfig);
  10. // 如果该路由不用进行权限校验,登录状态下登陆页除外
  11. // 因为登陆后,无法跳转到登陆页
  12. // 这部分代码,是为了在非登陆状态下,访问不需要权限校验的路由
  13. const targetRouterConfig = routerConfig.find(
  14. (item) => {
  15. return item.path.replace(/\s*/g,"") === pathname
  16. }
  17. );
  18. if (targetRouterConfig && !targetRouterConfig.auth && !isLogin) {
  19. const { component } = targetRouterConfig;
  20. return <Route exact path={pathname} component={component} />
  21. }
  22. if (isLogin) {
  23. // 如果是登陆状态,想要跳转到登陆,重定向到主页
  24. if (pathname === "/login") {
  25. return <Redirect to="/" />;
  26. } else {
  27. // 如果路由合法,就跳转到相应的路由
  28. if (targetRouterConfig) {
  29. return (<Route path={pathname} component={targetRouterConfig.component} />);
  30. } else {
  31. // 如果路由不合法,重定向到 404 页面
  32. return <Redirect to="/404" />;
  33. }
  34. }
  35. } else {
  36. // 非登陆状态下,当路由合法时且需要权限校验时,跳转到登陆页面,要求登陆
  37. if (targetRouterConfig && targetRouterConfig.auth) {
  38. console.log('跳转登录登录')
  39. return <Redirect to="/login" />;
  40. } else {
  41. // 非登陆状态下,路由不合法时,重定向至 404
  42. return <Redirect to="/404" />;
  43. }
  44. }
  45. }
  46. }
  47. export default FrontendAuth

使用高阶组件

  1. import React from 'react';
  2. import {Switch, BrowserRouter} from 'react-router-dom'
  3. // 你的高阶组件
  4. import FrontendAuth from './FrontendAuth'
  5. // 你的路由表
  6. import {routerObj} from '../views/index'
  7. function router() {
  8. return (
  9. <BrowserRouter>
  10. <Switch>
  11. <FrontendAuth routerConfig={routerObj} />
  12. </Switch>
  13. </BrowserRouter>
  14. );
  15. }
  16. export default router;

后续会更新如何自动化配置路由表,以及在路由中如何自定义懒加载和预加载页面和组件
(最近在用react重新开发博客-。-有空在更)

发表评论

表情:
评论列表 (有 0 条评论,848人围观)

还没有评论,来说两句吧...

相关阅读

    相关 react前置守卫

    react中一切皆组件--2018.7.18 目标:自定义user界面的前置路由守卫,当用户点击要进入user组件时,路由守卫发起判断,如果条件满足则进入,否则跳转至l

    相关 react 守卫

    原理 `react路由守卫` 是通过 `高阶组件(HOC)` 实现的 因此针对不同的情况就要封装不同的 `HOC` 接下来展示一个有关登录权限的路由守卫例子 demo