1. Static route vs. dynamic route

In Web front-end development, we often have to deal with page routing. Traditionally, routing information is centrally configured in one place, which we can call “static routing” or “centralized routing.” Take the React-Router V3 as an example, the code is similar to the following:

import { Router, Route, IndexRoute, browserHistory } from 'react-router'

const App = () => (
  <Router history={browserHistory}>
    <Route path="/" component={RootPage}>
      <IndexRoute component={HomePage} />
      <Route path="/users" component={UsersPage} />
    </Route>
  </Router>
)

render(<App />, document.getElementById('app'))
Copy the code

As you can see, all the routing information is configured on the top-level component of the program, and the different levels are represented through nested relationships. However, the React-Router V4 version has been revolutionized to make it more in line with react’s idea of “componentization,” which we can call “dynamic routing,” or, to borrow blockchain terminology, “decentralized routing.” The code rewritten with V4 looks like this:

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

const App = () => (
  <BrowserRouter>
    <RootPage />
  </BrowserRouter>
)

const RootPage = () => (
  <div>
    <Route path="/" exact component={HomePage} />
    <Route path="/users" component={UsersPage} />
  </div>
)

render(<App />, document.getElementById('app'))
Copy the code

It can be found that the routing configuration is no longer all located in the top component, but scattered in different components, through the nested relationship of components to realize the routing hierarchy. In addition, unlike static routing, which defines all pages in advance, dynamic routing can dynamically determine which components to render according to the path matching results during rendering, which can fully realize page reuse and reduce repeated rendering. The following describes the components of React – Router V4.

2.Router

React-router actually makes use of the browser’s History API internally, so in V3 we need to pass a history property in the top-level <Router> component. A <BrowserRouter> component was wrapped for us in v4, and we need to wrap it in the outermost layer of all components:

import { BrowserRouter } from 'react-router-dom'const App = () => ( <BrowserRouter> ... . </BrowserRouter> )Copy the code

There is also a <HashRouter> component that is no longer recommended for compatibility with previous versions of browsers.

3. Routes are matched

Route matching mainly involves two components: <Route> and <Switch>, which are described below.

3.1 < Route >

The

component contains three classes of properties: matching properties, rendering methods, and routing properties.

3.1.1 Matching Attributes

These properties are used to set url matching rules.

(1) Path: the route matches the regular expression

For example:

<Route path=’/’ /> : Matches paths starting with /, such as /, /login, /login/ Alice

< the Route path = ‘/ login: username / > : can match/login/Alice, parameters can be achieved by props. Match. Params. The username

(2) exact

For example:

<Route path=’/’ exact /> : matches only /, but not /login

The <IndexRoute> component was removed in version V4, so if you want to display a page in the root path, you can use the following method:

<div>
  <Route path="/"exact component={HomePage} /> ... . </div>Copy the code

(3) strict: strict match

If the path ends with a /, the URL must also have a/to match. For example:

<Route path=’/login/’ strict /> : /login/ can be matched but /login cannot be matched

(4) Sensitive

3.1.2 Rendering method

These properties specify how to render after the match has been routed.

(1) Component: render component

This is the most common way to render a specified component when routing matches

<Route path=’/users’ component={UsersPage} />

(2) render: inline

Component creates new elements with React. CreateElement and mounts them to the DOM. This is inefficient if you need frequent updates, so you can use inline rendering instead.

<Route path='/users'render={props => ( <div> <Component {... props}/> </div> )}/>Copy the code

(3) Children: render child elements according to path matching results

While the previous two render methods only render if path matches, the Children render method is special in that it works with children and only returns a match result. You can decide how to render the children based on the match result. For example, in a list we want to highlight elements that are matched:

<ul>
  <ListItemLink to="/somewhere" />
  <ListItemLink to="/somewhere-else"/> </ul>; const ListItemLink = ({ to, ... rest }) => ( <Route path={to} children={({ match }) => ( <li className={match ?"active" : ""}> <Link to={to} {... rest} /> </li> )} /> );Copy the code
3.1.3 Route Attributes

These properties can be accessed via props in the component to be rendered.

(1) match

The match attribute contains parameters related to route matching:

  • Params: parameter key-value pairs (e.g. Username)
  • IsExact: Indicates whether exact matches are specified.
  • Path: regular expression (such as /login/:username)
  • Url: the part that matches the path (inbound /login/ Alice)

(2) location

Location contains parameters related to the current URL:

  • Pathname: indicates the current URL
  • Search: a query string in a URL (such as? The username = a&sort = b)
  • State: carries a specific state parameter, which is an object (e.g. {XXX: ‘XXX’})

(3) history

History is the browser-provided History API, which provides routing functions:

  • Push (path, [state]) : page jump
  • Replace (PATH, [state]) : redirection
  • Go (n) : go to the NTH page
  • GoBack () : equivalent to go(-1)
  • GoForward () : equivalent to go(1)

3.2 < Switch >

What if we wanted to set up a set of routing matching rules, rendering only the first component that matches? This is where you need the

component.

contains a set of

or

that renders only the first Route that matches.



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

<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/about" component={About}/>
  <Route path="/:user" component={User}/>
  <Route component={NoMatch}/>
</Switch>
Copy the code

4. The navigation

The React – Router provides a set of navigation components that are basically a wrapper around the tag. It mainly includes three types:

  • : Final render to
  • : Path is highlighted when matched

  • : Redirects

For example:

import { Link, NavLink } from 'react-router-dom'

<Link to="/about">About</Link>
<NavLink to="/faq" activeClassName="selected">
  FAQs
</NavLink>
Copy the code

React-router also provides some other tools, such as react-loadable, which supports dynamic import of components, and react-transition-group, which supports CSS transitions.

I conclude with a mind map: