Implementation of react routing guard (routing interception)

Implementation of react routing guard (routing interception)

React is different from Vue. It implements route interception by setting meta characters in the route. When using Vue, the framework provides a routing guard function, which is used to perform some verification work before entering a certain route. If the verification fails, it jumps to the 404 or login page, such as the beforeEnter function in Vue:

...
router.beforeEach(async(to, from, next) => {
    const toPath = to.path;
    const fromPath = from.path;
})
...

The basic idea of ​​react to implement routing interception is to use the render function of Route. Interception is achieved by judging the interception conditions to realize the jump of different components. In previous versions, React Router also provided a similar onEnter hook, but in React Router 4.0, this method was cancelled. React Router 4.0 and later uses declarative components. Routers are components. To implement the routing guard function, we have to write it ourselves.
Without the routing guard, the Router component looks like this:

import * as React from 'react';
import { HashRouter,Switch,Route,Redirect } from 'react-router-dom';
 
import Index from "./page/index";
import Home from "./page/home";
import ErrorPage from "./page/error";
import Login from "./page/login";
 
export const Router = () => (
    <HashRouter>
        <Switch>
            <Route path="/" exact component={Index}/>
            <Route path="/login" exact component={Login}/>
            <Route path="/home" exact component={Home}/>
            <Route path="/404" exact component={ErrorPage}/>
            <Redirect to="/404" />
        </Switch>
    </HashRouter>
);

The Router component above contains three pages:

Login Home Page
404 page and four routes:
Root Router Login Router Home Router
404 routes Among them, the root route and the /home route are both directed to the home page route.
The above is a basic route definition that can jump back and forth between the login/home page and the 404 page, but there are also some problems:
In the non-logged-in state, you can directly jump to the home page. In the logged-in state, you can also enter the /login route to jump to the login page. Now, we want to complete the following function:
In the non-logged-in state, you cannot jump directly to the home page. If you jump to the home page in the non-logged-in state, you need to redirect to the login route. In the logged-in state, you cannot jump to the login page. If you jump to the login page in the logged-in state, you need to redirect to the home page route. To complete this function, there are two solutions:
In each component, jump according to the history object on props to perform global routing guard processing

First, create a routerMap.js file in the root directory src. The code is as follows:
Setting auth to true means that the route requires permission verification.

/**
 * Define the routing component and set auth to true, indicating that the route requires permission verification*/

import Admin from "./pages/Admin";
import Login from "./pages/Login";
import Error from "./pages/Error";

export const routerMap = [
    {path: "/", name: "admin", component: Admin, auth: true},
    {path: "/login", name: "Login", component: Login},
    {path: "/error", name: "error", component: Error},
];

All routing jumps are completed by the FrontendAuth high-order component proxy. Here is the implementation of the FrontendAuth.js component:

/**
 * Routing guard verification */
import React, {Component} from "react";
import {Route, Redirect} from "react-router-dom";

class FrontendAuth extends Component {
    // eslint-disable-next-line no-useless-constructor
    constructor(props) {
        super(props);
    }

    render() {
        const {routerConfig, location} = this.props;
        const {pathname} = location;
        const isLogin = localStorage.getItem("user");
        console.log(pathname, isLogin);
        console.log(location);
        // If the route does not need permission check, except for the login page in the logged-in state // Because after logging in, you cannot jump to the login page // This part of the code is to access routes that do not require permission check in the non-logged-in state const targetRouterConfig = routerConfig.find(
            (item) => item.path === pathname
        );
        console.log(targetRouterConfig);
        if (targetRouterConfig && !targetRouterConfig.auth && !isLogin) {
            const {component} = targetRouterConfig;
            return <Route exact path={pathname} component={component}/>;
        }
        if (isLogin) {
            // If you are logged in, you want to jump to the login page and redirect to the home page if (pathname === "/login") {
                return <Redirect to="/"/>;
            } else {
                // If the route is legal, jump to the corresponding route if (targetRouterConfig) {
                    return (
                        <Route path={pathname} component={targetRouterConfig.component}/>
                    );
                } else {
                    // If the route is illegal, redirect to the 404 page return <Redirect to="/error"/>;
                }
            }
        } else {
            // In the non-login state, when the route is legal and requires permission verification, jump to the login page and require login if (targetRouterConfig && targetRouterConfig.auth) {
                return <Redirect to="/login"/>;
            } else {
                // In the non-logged in state, when the route is illegal, redirect to 404
                return <Redirect to="/error"/>;
            }
        }
    }
}

export default FrontendAuth;

Then, define the Router component. In App.js, this component is the result of being wrapped by a higher-order component:

import './App.less';
import React, {Fragment} from "react";
import {Switch} from 'react-router-dom'
import FrontendAuth from "./FrontendAuth";
import {routerMap} from "./routerMap";

function App() {
    return (
        <Fragment>
            {/*Only match one, if the match succeeds, do not match further, high efficiency*/}
            <Switch>
                <FrontendAuth routerConfig={routerMap}/>
            </Switch>
        </Fragment>
    );
}

export default App;

test

This is the end of this article about the implementation of react routing guard (route interception). For more relevant react routing guard content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the redirection methods of each version of React routing
  • React-router v4: How to use history to control route jumps
  • Detailed explanation of how react obtains routing parameters in components
  • How to use nested routes in react-router4
  • Several implementation solutions for lazy loading of React routes
  • Implementation of React-router4 route monitoring
  • Summary of React-router v4 routing configuration method
  • How to implement React routing authentication
  • Detailed explanation of react routing configuration

<<:  Specific use of Linux dirname command

>>:  MySql knowledge points: transaction, index, lock principle and usage analysis

Recommend

My personal summary of mysql 5.7 database installation steps

1.mysql-5.7.19-winx64.zip (this is the free insta...

CSS3 overflow property explained

1. Overflow Overflow is overflow (container). Whe...

Sample code for implementing two-way authentication with Nginx+SSL

First create a directory cd /etc/nginx mkdir ssl ...

Summary of 9 excellent code comparison tools recommended under Linux

When we write code, we often need to know the dif...

Detailed explanation of nginx's default_server definition and matching rules

The default_server directive of nginx can define ...

How to start multiple MySQL instances in CentOS 7.0 (mysql-5.7.21)

Configuration Instructions Linux system: CentOS-7...

Detailed explanation of mysql replication tool based on python

Table of contents 1. Introduction Second practice...

Example code of Vue3 encapsulated magnifying glass component

Table of contents Component Infrastructure Purpos...

Introduction to Docker containers

Docker Overview Docker is an open source software...

MySQL Basic Tutorial: Detailed Explanation of DML Statements

Table of contents DML statements 1. Insert record...

Writing a web calculator using javascript

This article mainly records the effect of using j...

Analysis of the implementation process of three modes of VMWare network adapter

Three modes Bridged (bridge mode), NAT (network a...

How to determine if the Linux system is installed on VMware

How to determine whether the current Linux system...