One, foreword

This article introduces the React router, which is officially maintained and extremely important in development.

Principle of front-end routing

How does front-end routing map urls to content? Listen for URL changes.

2.1 the URL hash

The hash of a URL is an anchor point, which essentially changes the window.location.href property. We can directly assign location.hash to change the href, and the page will not refresh.

<div id="app">
  <a href="#/home">home</a>
  <a href="#/about">about</a>
  <div class="router-view"></div>
</div>

<script>
  // 1. Obtain router-view
  const routerViewEl = document.querySelector(".router-view");

  // 2. Listen on hashchange
  window.addEventListener("hashchange".() = > {
    switch(location.hash) {
      case "#/home":
        routerViewEl.innerHTML = "home";
        break;
      case "#/about":
        routerViewEl.innerHTML = "about";
        break;
      default:
        routerViewEl.innerHTML = "default"; }})</script>
Copy the code

2.2HTML5的History

History is new to H5, and there are six ways to change urls without refreshing the page.

  1. ReplaceState: replaces the original path.
  2. PushState: uses the new path.
  3. PopState: rollback of a path.
  4. Go: to change the path forward or backward;
  5. Forword: change path forward;
  6. Back: Changes the path backwards.

Third, the react – the router

The three most popular frameworks (React, Vue, and Angular) all have their own routes. Since React Router version 4, routes are not managed in a single package.

  1. React-router is the core code of the router.
  2. React-router-dom is for browsers;
  3. React-router-native is for native applications;

3.1 install the react – the router

Yarn add react-router-dom install react-router-dom automatically install react-router dependencies.

3.2 Basic Use of Router

The React-Router provides some components for us to use:

BrowserRouter and HashRouter
  • The Router includes listening for path changes and passes the corresponding paths to the child components.
  • BrowserRouter uses history mode;
  • HashRouter uses hash mode;
The Link and NavLink:
  • A typical jump to a path uses a Link component, which ends up being rendered as an A element;
  • NavLink adds style attributes on top of Link (learn more later);
  • To property: The most important property in Link, used to set the path to jump to;
The Route:
  • Route is used to match paths.
  • Path property: used to set the matched path;
  • Component property: Render component after setting match to path;
  • Exact: exact matching. Only when the exact path is matched, the corresponding component will be rendered.
import React, { PureComponent } from 'react';

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

import Home from './pages/home';
import About from './pages/about';
import Profile from './pages/profile';

export default class App extends PureComponent {
  render() {
    return (
      <BrowserRouter>
        <Link to="/">Home page</Link>
        <Link to="/about">about</Link>
        <Link to="/profile">my</Link>

        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/profile" component={Profile} />
      </BrowserRouter>)}}Copy the code

The use of 3.3 NavLink

The NavLink component provides apis for active routing states

  • ActiveStyle: Active (matching) style;
  • ActiveClassName: class added when active;
  • Exact: Whether the match is accurate.

Demonstrate activeStyle, the route is activated in red

<NavLink exact to="/" activeStyle={{color: "red"}} > home page < / NavLink ><NavLink to="/about" activeStyle={{color: "red}} ">about</NavLink>
<NavLink to="/profile" activeStyle={{color: "red}} ">my</NavLink>
Copy the code

React adds the active class by default after the path matches.

.active {
    color: red
}
Copy the code

Custom class name:

<NavLink exact to="/" activeClassName="link-active"> home page < / NavLink ><NavLink to="/about" activeClassName="link-active">about</NavLink>
<NavLink to="/profile" activeClassName="link-active">my</NavLink>
Copy the code
.link-active {
    color: red
}
Copy the code

3.4 the use of the Switch

Components corresponding to routes whose paths are matched in the React-Router will be rendered. But in practice, we often want to have an exclusive mindset:

  • As soon as the first one matches, the next one should not continue to match;
  • In this case, we can use Switch to wrap all routes.
<Switch>
  <Route exact path="/" component={Home} />
  <Route path="/about" component={About} />
  <Route path="/profile" component={Profile} />
  <Route path="/:userid" component={User} />
  <Route component={NoMatch} />
</Switch>
Copy the code

3.5 the use of Redirect

Redirect Redirect is used to Redirect routes. When this component is present, it performs a Redirect to the corresponding to path, for example, determining whether a user is logged in. Create a user.js file

import React, { PureComponent } from 'react'
import { Redirect } from 'react-router-dom';

export default class User extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      isLogin: false}}render() {
    return this.state.isLogin ? (
      <div>
        <h2>User</h2>
        <h2>Username: Coderwhy</h2>
      </div>) :<Redirect to="/login"/>}}Copy the code

Define routes in app.js

<switch>... Other routes <Route path="/login" component={Login} />
</switch>
Copy the code

3.6 Route Nesting

Assuming two more child pages are included in the child page, the sample code looks like this:

import React, { PureComponent } from 'react';
import { Route, Switch, Link } from 'react-router-dom';

function AboutProduct(props) {
  return (
    <ul>
      <li>List of Goods 1</li>
      <li>Item List 2</li>
      <li>Item List 3</li>
    </ul>)}function AboutMessage(props) {
  return (
    <ul>
      <li>Message List 1</li>
      <li>Message List 2</li>
      <li>Message List 3</li>
    </ul>)}export default class About extends PureComponent {
  render() {
    return (
      <div>
        <Link to="/about">goods</Link>
        <Link to="/about/message">The message</Link>

        <Switch>
          <Route exact path="/about" component={AboutProduct} />
          <Route path="/about/message" component={AboutMessage} />
        </Switch>
      </div>)}}Copy the code

3.7 Route Redirection

  • If the component is being routed through, you can get the History, location, and match objects in props.
  • What if it’s a normal button inside a component and you want to click to jump to a page?

React-router allows us to access relevant information through higher-level components. If we want to get the history object in the component, two conditions must be met:

  • The component must be wrapped within the Router component;
  • Components are wrapped with withRouter high-order components;

3.8 Parameter Transfer

There are three ways to pass parameters

  • Dynamic routing;
  • Search passes parameters;
  • To pass object;

3.8.1 Dynamic Routing The route parameters are not fixed

  • For example, the /detail path corresponds to the detail component
  • If we put<route />If the path is written as /detail/:id, both /detail:123 and /detail: ABC will match the route.

When using dynamic routing, we can use this.props. Match-params to get the parameters passed. Search passes the query argument. We can write the query argument in the jump path

<NavLink to="/detail2? name=why&age=18"> details2</NavLink>
Copy the code

Use the search parameters, can use this. Props. Location. Search to get the needed parameters to the incoming object reference

<NavLink to={{
    pathname: "/detail2".query: {name: "kobe".age: 30},
    state: {height: 1.98.address: "Los Angeles"},
    search: "? apikey=123"}} > for details2
</NavLink>
Copy the code

To pass parameters using search, you can call this.props. Location to get the required parameters