React Router

React-router: The react-router library contains many core code related to routing functions

React-router-dom: Use the core library, combined with the actual page, to achieve page routing related functions

So we usually install the React-router-DOM library

Two modes of routing

As we all know, the url address (e.g. https://www.suressk.com:443/article?uid=sures&id=1008#hash) consists of the following parts:

  1. Network Protocol (schema) :https (http / https / fileEtc.)
  2. The host name (host) :www.suressk.com(generally haveThe IP address.The domain name.Default values (such as localhost).The name of the computer on the LANEtc.)
  3. The port number (port) :443 (HTTP default 80.HTTPS by default, 443)
  4. Access path (path) :/article
  5. Query parameters (query / search) :? uid=sures&id=1008
  6. Hash (hash / The anchor) :#hash

Hash Router

The component to display is determined by the hash value in the URL address

Since hash changes do not cause page refreshes, it is compatible with older browsers

Browser History Router

With the advent of HTML5, the History API was added, giving browsers the ability to change paths without refreshing the page. History is the History of the browser. It is stored in a stack. Every time we access a path, it adds a path record to the stack

history:

  1. History. length: displays the number of historical records on the current page

  2. PushState (data, title, URL) : adds a new record to the current history stack

    • data: Additional data information
    • title: Page title (not supported by most browsers)
    • url: Indicates the new path address
  3. History.replacestate (data, title, URL) : Replaces the current history of the history stack

Thus, we can decide which component to render based on the path

Routing component

The React-Router provides us with two important components: router and Route, as well as several other components

The Router components

It doesn’t do anything by itself, only provides routing mode configuration; This component generates a context that provides some useful objects and methods. React-router-dom provides the following two components:

  1. HashRouter: Practical hash pattern matching

  2. BrowserRouter: Practical BrowserHistory mode matching

Typically, only one Router component is used and the entire page is wrapped around it

The Route component

It has two important properties: path and Component:

  1. Path: The path rule to match (address matching involves the following “dynamic path “), or it can be a path regular array

    • The default is case insensitive (can be setThe sensitive property is trueTo match the pathsCase sensitive)
    • The default is fuzzy matching. If the path exists, the match is considered successfulThe exact attribute is trueTo match exactly)
    • If you don’t set itpath, any path is matched
  2. Component: components to be displayed if the path is successfully matched

  3. The children of the Route:

    • If the React element matches the Route component, children will be displayed regardless of whether the path matches successfully or not, and the Route component’s component property will be ignored

    • Pass a function that takes multiple arguments (from the context in which the Router component was generated) and return the React element. The React element must be displayed, and the Route component’s Component property will be ignored

import React from 'react'
import {BrowserRouter as Router, Route} from 'react-router-dom'
function CompA() {
    return <div>CompA</div>
}
function CompB() {
    return <div>CompB</div>
}
function CompC() {
    return <div>CompC</div>
}
export default function App() {
    return (<Router>
        <Route path='/a' component={CompA} />
        <Route path='/b' component={CompB}>
            <div style={{ color: "#f40}} ">Route Children Prop</div>
        </Route>
        <Route component={CompC} />
    </Router>)}Copy the code

RouteA component can be written anywhere, as long as it isRouterThe descendant of the component

The Switch component

It will match the path in sequence, and if the path matches successfully, it will not match any further (by default, it will match all the paths of the Route component).

Since the Switch component loops through all the child elements (in the order in which the Route component was written), if the match is successful, the corresponding component is rendered and the loop is stopped. Therefore, the Switch subcomponent cannot be a component other than the Route and Redirect components

// For example:
import React, { memo } from 'react'
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'

function CompA() {
    return <div>CompA</div>
}
function CompB() {
    return <div>CompB</div>
}
function CompC() {
    return <div>CompC</div>
}

function Task() {
    return (<Router>
        <Switch>
            <Route path="/a/b">
                <CompB />
            </Route>
            <Route path="/a" component={CompA}>
                <div style={{ color: "#f40}} ">Route Children Prop</div>
            </Route>
            <Route component={CompC} />
        </Switch>
    </Router>)}export default memo(Task)
Copy the code

In this example, when we visit the local server address /a/b path, you will see that the page is rendered as follows: CompB: The/A path shows the red Route Children Prop, but the Switch component match stops after the CompB component is displayed

Routing information

The Router component will create a Context and inject some information into the Context. This Context is hidden from the developer, and the Route component matches the path. The Route component passes the information in the Context as properties to the corresponding component:

history

  • A non-window.history object that we can use to do things like jump without refreshing

  • push(relativePath, data?) : pushes a new address onto the stack (the history stack). The first parameter is the relative path of the jump. The second parameter is the jump in the past state of additional data (behind by props. History. The location. The state, but the state data depends on the jump, if direct access to the jump of the path, the state data is null)

  • replace(relativePath, data?) : Replaces the current record in the history stack with a new address

  • Go ()/forward()/back() : Use the same method as in window.history

location

  • This is the same object as props. History. Location, which contains information about the current address (search/hash/pathname/state). We usually use a third-party library called Query-string to parse the parameter data:

  • Such as the location. The search:? {a: 1, b: 2, c: 3}

  • For example, location.hash: #d=4&e=5

match

  • The information about route matching is saved

  • IsExact: Indicates whether the current Route path matches the Route component path, regardless of whether the Route component is configured with the exact attribute

  • Params: Collects data from the location of the address bar parameters based on the dynamic parameters configured by the Route component. For example:

    • ; params ={year: ‘2021’, month: ‘7’, day: undefined}; params ={year: ‘2021’, month: ‘7’, day: undefined}; If the path is /news/suressk/7, the path fails to match

  • “/news/:year(\d+)/:month? /:day?” )

  • Url: Indicates the actual matched route path

The React-Router uses path-to-regexp to parse the path regular string, parsing it into a real regular expression

In general, data is passed to the page in the following ways:

  1. Using state: Depends on passing data when jumping manually using the History object

  2. Use search: Carry /news? With the query parameter in the address bar. year=2021&month=7&day=21

  3. Hash: Add data to the hash value in the address bar /news#year=2021&month=7&day=21

  4. Use Params: Fill the data in the path /news/2021/7/21