A. React – the router

React-router depends on react-router-dom

To use react-router, you must install the react-router-dom

npm i react-router-dom
Copy the code

React-router Basic components

  • BrowserRouter or 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.

The most basic use

import React, { PureComponent } from "react"; import { BrowserRouter, Route, NavLink, Switch } from "react-router-dom"; import About from "./About"; import Home from "./Home"; import Profile from "./Profile"; import "./App.css"; Class App extends PureComponent {render() {return (<BrowserRouter> <Link to="/"> home </Link> <Link to="/about"> </Link> <Link to="/profile"> my </Link> <Route exact path="/" Component ={Home} /> <Route path="/about" component={about} /> <Route path="/profile" component={Profile} /> </BrowserRouter> ); } } export default App;Copy the code

The use of NavLink

When the path is selected, the corresponding a element turns red

  • ActiveStyle: Active (matching) style;
  • ActiveClassName: class added when active;
  • Exact: Whether the match is accurate.
<NavLink to="/" activeStyle={{color: "red"}}> </NavLink> </NavLink to="/profile" activeStyle={{color: "red"}}> My </NavLink>Copy the code

When the NavLink component is used, the active route (a tag) will have an additional active class, whose name can be customized.

The use of the Switch

  • Provides a unique mapping of a path to a component
  • As soon as the first one matches, the next one should not continue to match;
<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

The use of the Redirect

Redirect Redirect is used to Redirect routes. When this component is present, it performs a Redirect to the corresponding to path:

Here’s an example of how to use this:

  • The User page is displayed.

  • However, there is an isLogin in the User interface to record whether the User is logged in:

    • True: then display the user name;
    • False: Directly redirect to the login page.

The Route corresponding to the Login page is defined in advance in app.js:

<Switch> ... Other Route <Route path="/login" component={login} /> <Route Component ={NoMatch} /> </Switch>Copy the code

Write the corresponding logic code in user.js:

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

3. The react – senior router

Nested routing

In development, there are nested relationships between routes.

Here we assume that the About page has two contents:

  • Item list and message list;
  • Click on different links to jump to different places, display different content;
import React, { PureComponent } from 'react'; import { Route, Switch, Link } from 'react-router-dom'; Function AboutProduct(props) {return (<ul> <li> props 1</li> <li> <li> props 2</li> <li> </li>)} function AboutProduct(props) {return (<ul> <li> <li>)} function AboutMessage(props) {return (<ul> <li> props 1</li> <li> Props 2</li> <li> props 3</li> </ul>)} export default class About Extends PureComponent {render() {return (<div> <Link to="/about"> merchandise </Link> <Link to="/about/message"> message </Link> <Switch> <Route exact path="/about" component={AboutProduct} /> <Route path="/about/message" component={AboutMessage} />  </Switch> </div> ) } }Copy the code

Manual jump

In addition to using Link and NavLink, you can also use JavaScript to jump.

You must get the History object

Access method

  • Method 1: If the component is directly jumped to through the route, you can directly obtain the history, location, and match objects.
  • Method 2: If the component is a normal rendered component, wrap it with withRouter and get the history, location, and match objects.

Passing parameters

There are three ways to pass parameters:

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

Dynamic routing

<div> ... <NavLink to="/detail/abc123"> </NavLink> <Switch>... <Route path="/detail/:id" component={detail}/> <Route component={NoMatch} /> </Switch> </div>Copy the code

You can get the ID directly from the match object; Search transfer parameter

<NavLink to="/detail2? Name =why&age=18"> detail2 </NavLink> <Switch> <Route path="/detail2" component={detail2}/> </Switch>Copy the code

Access to the search

import React, { PureComponent } from 'react' export default class Detail2 extends PureComponent { render() { console.log(this.props.location.search); / /? name=why&age=18 return ( <div> <h2>Detail2:</h2> </div> ) } }Copy the code

To pass object To can pass an object directly

<NavLink to={{pathName: "/detail2", query: {name: "Kobe ", age: 30}, state: {height: 1.98, address:" Los Angeles "}, search: "? Apikey =123"}}> </NavLink>Copy the code

Get parameters:

import React, { PureComponent } from 'react'

export default class Detail2 extends PureComponent {
  render() {
    console.log(this.props.location);

    return (
      <div>
        <h2>Detail2:</h2>
      </div>
    )
  }
}
Copy the code

4. The react – the router – config

So far all of our Route definitions are done directly using the Route component and adding attributes.

However, this approach can become very confusing, and we want to centralize all routing configurations in one place:

  • You can use react-router-config to do this.

Install the react – the router – config:

npm install react-router-config
Copy the code

Router /index.js:

import Home from ".. /pages/home"; import About, { AboutMessage, AboutProduct } from ".. /pages/about"; import Profile from ".. /pages/profile"; import Login from ".. /pages/login"; import User from ".. /pages/user"; import Detail from ".. /pages/detail"; import Detail2 from ".. /pages/detail2"; import NoMatch from ".. /pages/nomatch"; const routes = [ { path: "/", exact: true, component: Home }, { path: "/about", component: About, routes: [ { path: "/about", exact: true, component: AboutProduct }, { path: "/about/message", component: AboutMessage }, ] }, { path: "/profile", component: Profile }, { path: "/login", component: Login }, { path: "/user", component: User }, { path: "/detail/:id", component: Detail }, { path: "/detail2", component: Detail2 }, { component: NoMatch } ]; export default routes;Copy the code

Used where the route group needs to be invoked

{renderRoutes(routes)}
Copy the code

If you need to route a jump, you need to use the renderRoutes function in the child component:

  • There is an extra component in the route component to jump tothis.props.routeProperties;
  • therouteProperty indicates the current route object to be jumped to. You can obtain it by using this propertyroutes;
Export default class About extends PureComponent {render() {return (<div> <Link to="/ About "> commodity </Link> <Link </Link> {renderRoutes(this.routes.routes)} </div>)}}Copy the code

A matchRoutes helper function is also provided in react-router-config:

  • matchRoutes(routes, pathname)Pass in an array of routing objects to get all the matching paths;
const routes = matchRoutes(this.props.route.routes, "/about");
console.log(routes);
Copy the code