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

mysql command line script execution example

This article uses an example to illustrate the ex...

Solution to the problem of eight hours difference in MySQL insertion time

Solve the problem of eight hours time difference ...

A brief talk about JavaScript Sandbox

Preface: Speaking of sandboxes, our minds may ref...

Detailed tutorial on installing phpMyAdmin on Ubuntu 18.04

We will install phpMyAdmin to work with Apache on...

Detailed explanation of the basic use of Apache POI

Table of contents Basic Introduction Getting Star...

SystemC environment configuration method under Linux system

The following is the configuration method under c...

The difference between Vue interpolation expression and v-text directive

Table of contents 1. Use plugin expressions 2. Us...

Search engine free collection of website entrances

1: Baidu website login entrance Website: http://ww...

Detailed steps to change the default password when installing MySQL in Ubuntu

Step 1: Enter the directory: cd /etc/mysql, view ...

Specific use of the wx.getUserProfile interface in the applet

Recently, WeChat Mini Program has proposed adjust...

jQuery implements clicking left and right buttons to switch pictures

This article example shares the specific code of ...

MySql 8.0.16-win64 Installation Tutorial

1. Unzip the downloaded file as shown below . 2. ...

20 Signposts on the Road to Becoming an Excellent UI (User Interface) Designer

Introduction: Interface designer Joshua Porter pub...