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

How to change the root password in MySQL 5.7

Starting from MySQL 5.7, many security updates ha...

Tutorial on using hyperlink tags in XHTML

Hyperlink, also called "link". Hyperlin...

Detailed explanation of JavaScript axios installation and packaging case

1. Download the axios plugin cnpm install axios -...

vue perfectly realizes el-table column width adaptation

Table of contents background Technical Solution S...

Vue implements form data validation example code

Add rules to the el-form form: Define rules in da...

Detailed explanation of Angular routing basics

Table of contents 1. Routing related objects 2. L...

How to use Nginx to handle cross-domain Vue development environment

1. Demand The local test domain name is the same ...

MySQL8 Installer version graphic tutorial

Installation The required documents are provided ...

How to install suPHP for PHP5 on CentOS 7 (Peng Ge)

By default, PHP on CentOS 7 runs as apache or nob...

How to set a fixed IP address for a VMware virtual machine (graphic tutorial)

1. Select Edit → Virtual Network Editor in the me...

Recommend some useful learning materials for newbies in web design

Many people also asked me what books I read when ...

Detailed steps for creating a Vue scaffolding project

vue scaffolding -> vue.cli Quickly create a la...

Pure CSS3 code to implement a running clock

Operation effectCode Implementation html <div ...

Delegating Privileges in Linux Using Sudo

Introduction to sudo authority delegation su swit...

Introduction to the use of em in elastic layout in CSS3: How many pixels is 1em?

I have been using CSS for a long time, but I have...