preface

React-router is basically a navigation system.

Why is a React-Router needed

The source of the Router is SPA applications, which are commonly used single-page applications such as ReactJS and VueJS.

Because the single-page application is no longer each page to jump to the server request code, but a set of all requests back, page jump needs to be carried out locally, so there is a Router.

Let’s start with a complete set of code

import React from 'react' import { lazy } from 'react' import { BrowserRouter, Redirect, Route, Switch } from 'react-router-dom' import { useAuth } from './authContext' const Login = lazy(() => import('.. /pages/login')) const BlogList = lazy(() => import('.. /pages/blogList')) const routes = [ { title: 'login', name: 'login', path: '/login', component: Login }, { title: 'blog', name: 'blog', path: '/blog', children: [ { title: 'list', name: 'blog-list', path: '/blog/list', component: BlogList }, ] }, ] const beforeEach = (route, auth) => { if (route.name ! == 'login') { if (! auth.token) { return <Redirect to="/login"></Redirect> } } return <route.component /> } const RouteView: React.FC = () => { const auth = useAuth() const getRouteRecursion = (v) => { return v.map((v) => { return ( <Route key={v.name} path={v.path}> {v.children ? getRouteRecursion(v.children) : beforeEach(v, auth)} </Route> ) }) } return ( <BrowserRouter> <Switch>{getRouteRecursion(routes)} <Redirect to="/qs/list"></Redirect> </Switch> </BrowserRouter> ) } export default RouteViewCopy the code

No doubt, this basically implements a set of basic functions, directly app.jsx import is good. The details of each introduced feature are described below.

Routing patterns

The routing pattern we used has two hash and history types, with the most obvious distinction being whether the link has # or not.

hash

Hash routing was adopted by early single-page applications. The hash route jumps to update the page by listening for changes in the anchor (#), so it does not trigger a page reload. Hash route Window. onhashchange monitors hash route changes to redirect pages without refreshing. Hash routing causes the page to display # and is therefore more used for ToB projects.

Advantages:

  • You can changeURLDoes not trigger a page reload
  • hashThe changed route history is recorded in thewindow.history

Disadvantages:

  • Due to the changeURLDoes not trigger page loading, so it is not conduciveSEOTo optimize the
  • It can only be changed by stringURL

history

The history mode route is implemented without refreshing through the window.history object newly added to the browser. History routing, while having some disadvantages, can be avoided with some optimizations and is therefore more used in ToC projects. Advantages:

  • The newURLCan be with the currentURLHomologous arbitraryURL, can also be with the currentURLconsistent
  • Available by parameterstateObjectAdds arbitrary type data to a record
  • Additional Settings availabletitleattribute
  • throughpushStatereplaceStateNo refresh is realized

Disadvantages:

  • Jumping to the same path will result in duplicate records in the stackURL
  • If the page is refreshed after a jump and then refreshed, the server is requested with a new path, and the server cannot match at this timeURL, resulting in a 404 message

use

Since our article is so new, we’ll leave hash routing out for now.

The basic use

  1. Create the base environment (skip existing projects)
Install router NPM install react-router --save NPM install React-router-dom --save # go to SRC and create router. JSX file CD SRC mkdir router. JSXCopy the code
  1. router.jsxThe introduction ofBrowserRouter

BrowserRouter is a routing container that determines which routing mode you use. Hash mode is HashRouter, and History mode is BrowserRouter

import { BrowserRouter } from 'react-router-dom'

const routeView = () => {
    return (
        <BrowserRouter>
        </BrowserRouter>
    )
}
Copy the code
  1. router.jsxThe introduction ofSwitch

The Switch is used to render only the first route if there are two routes with the same path

import { BrowserRouter, Switch, Route } from 'react-router-dom'

const routeView = () => {
    return (
        <BrowserRouter>
            <Switch>
            </Switch>
        </BrowserRouter>
    )
}
Copy the code
  1. router.jsxThe introduction ofRoute

Route renders a Route such as /login

import { BrowserRouter, Switch } from 'react-router-dom'
import Login from './pages/login'

const routeView = () => {
    return (
        <BrowserRouter>
            <Switch>
                <Route key='login' path='/login'>
                    <Login></Login>
                </Route>
            </Switch>
        </BrowserRouter>
    )
}
Copy the code

At this point, a simple route is complete, and we’ll introduce some advanced features that are commonly used.

Advanced features

Lazy (increased first screen loading speed)

Lazy allows us to import when we really need to render, making the first screen load faster. It’s also easy to use:

const Login = lazy(() => import('.. /pages/login'))Copy the code

Just use it as a normal component.

Separation of business logic

As we all know, the basic part of routing is framed, so we separate the paths from the business logic so that we can add routing and maintenance later.

Create a new map.js file that only needs to consider the data side.

import React from 'react' import { lazy } from 'react' const Login = lazy(() => import('.. /pages/login')) const BlogList = lazy(() => import('.. /pages/blogList')) const routes = [ { title: 'login', name: 'login', path: '/login', component: Login }, { title: 'blog', name: 'blog', path: '/blog', children: [ { title: 'list', name: 'blog-list', path: '/blog/list', component: BlogList }, ] }, ]Copy the code

Multi-layer routing

The implementation of multilayer routing is to write a recursive function, such as the getRouteRecursion function below.

import React from 'react'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import { routes } from './map'

const RouteView: React.FC = () => {
  const getRouteRecursion = (v) => {
    return v.map((v) => {
      return (
        <Route key={v.name} path={v.path} component={v.component}>
          {getRouteRecursion(v.children)}
        </Route>
      )
    })
  }
  
  return (
    <BrowserRouter>
        <Switch>
            {getRouteRecursion(routes)}
        </Switch>
    </BrowserRouter>
  )
}

export default RouteView

Copy the code

Routing guard

Routing guard sounds like a nice thing to do, which is basically to run a function before entering the route. The following paragraph is the guard to achieve the login page.

import React from 'react' import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom' import { routes } from './map' const beforeEach = (route, auth) => { if (route.name ! == 'login') { if (! Auth.token) {// Redirect is a Redirect, Return <Redirect to="/login"></Redirect>}} return <route.component />} const RouteView: React.fc = () => {const auth = useAuth() return (<Suspense fallback > < {<div> loading... </div>}> <Switch>{getRouteRecursion(routes)} {routes.map(v => {return beforeEach(v, auth)})} </Switch> </Suspense> </BrowserRouter> ) }Copy the code

redirect

Redirect Redirect is essentially a redirection of a route. The following paragraph represents a redirect to the home page if no path is matched.

import React from 'react' import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom' import { routes } from './map' const RouteView: React.fc = () => {const auth = useAuth() return (<Suspense fallback > < {<div> loading... </div>}> <Switch>{getRouteRecursion(routes)} {routes.map(v => ( <Route key={v.name} path={v.path} component={v.component}></Route> )) } </Switch> <Redirect to="/home"></Redirect> </Suspense> </BrowserRouter> ) }Copy the code

conclusion

That’s about it, I’ll add the hooks provided by react-Router, and the native use of history.