When learning React, I encountered many problems in routing: code splitting of routes, lazy loading of routes, route guarding, etc. Today I will mainly talk about how I solve these three problems. Also hope everybody big guy give directions…

First use the command line to install the following NPM packages:

NPM install react-router-dom // install react-router-dom // install react-router Module (I have version 5.2.0)Copy the code

This is my directory structure

The main entrance to the index. Js

import React from 'react';
import ReactDOM from 'react-dom';
import Routers from './router/index';

ReactDOM.render(
  <Routers/>,
  document.getElementById('root')
)
Copy the code

Create two page components to display:

To make permission management easy to understand, the page component is written simply:

Home/index.js

function login(){
  return "home";
}

export default login;
Copy the code

Login/index.js

function login(){
  return "home";
}

export default login;
Copy the code

Router: SRC = router; router: SRC = router;

Config.js (where routing is configured)

Import {lazy} from 'react' let config = [{name: '/', // name path: '/', // URL path authority: ["AUTH"], // exact: Component: lazy(() => import('../page/Home')) // lazy}, {name: 'Home', path: '/ Home', authority: {name:' Home', path: '/ Home', authority: ["AUTH"], exact: true, component: lazy(() => import('../page/Home')) }, { name: 'login', path: '/login', authority: [], exact: false, Component: lazy(() => import('../page/Login')},] export default config // ExportCopy the code

Index.js (in this case, route loading)

import { HashRouter, Switch, Route } from 'react-router-dom'; import React, {Suspense} from 'react'; import config from './config'; Import Authority from './ Authority '; Class Routers extends React.Com ponent {render () {return (< HashRouter > / / loading configuration can be according to their own love to use GIF or loading plug-ins < Suspense  fallback={<span>loading... < / span >} > < Switch > {/ * * import related routing configuration /} {config. The map ((r, key) => <Route exact={r.exact} key={key} path={r.path} render={(props) => { return <Authority {... {... props, r}}/> }}/>)} </Switch> </Suspense> </HashRouter> ); } } export default Routers;Copy the code

This enables code separation and lazy loading of configuration and routing control.

Now to achieve: when entering the home page, check whether the localStorage localStorage has the token field (you can later request the backend to determine whether the token is valid). If not or expired, redirect to the landing page.

Authority.js (mainly to implement the control of permissions)

import React from 'react'; import { Route, Redirect } from 'react-router-dom'; class Authority extends React.Component{ constructor(props){ super(); this.state = {... props}; } let {component, exact, path, authority} = this.state.r; const a = <Route component={component} exact={exact} path={path}></Route>; Return to current page if(! authority || authority.length === 0) return a; For (let I = 0; i < authority.length; If (authority[I] === "AUTH"){let token = localstorage.getitem ("token"); if(! Token) return <Redirect to="/login"></Redirect> // add business logic}} return a; } } export default Authority;Copy the code

In this way, a simple login permission judgment is realized. You can also add additional permissions, such as adding an order ID:

Add an order page in config.js

{name: 'order', path: '/order/:orderId', // obtain order ID authority: ["AUTH", "ORDER_ID"], false, component: lazy(() => import('.. /page/Order')) }Copy the code

Add a permission judgment in authority.js

For (let I = 0; i < authority.length; If (authority[I] === "AUTH"){let token = localstorage.getitem ("token"); if(! Token) return <Redirect to="/login"></Redirect>} if(authority[I] === "ORDER_ID"){ orderId } = this.state.match; // If (! 0) alert(" no such order "); // Add business logic}}Copy the code

Since the Order page adds two permission controls, one AUTH and one ORDER_ID. The logon is judged first according to the order of the permission array. If the order passes, the permission of orderId is judged. If both pass, the page will display normally. You can enter the following code on the console and test it:

localStorage.setItem("token", "123")
Copy the code

I React small white a piece, if there is a problem with the code, there is a problem that can be optimized, there is a problem with the idea, please leave a comment together to discuss, thank you!!