1. Basic use of the React route and 404not-found

Install (v5.2.0 react-router-dom is used here) :

yarn add react-router-dom 
Copy the code

Code examples:

//app.js
import React, {Component} from 'react';
import {BrowserRouter as Router,Route,Link,Switch} from "react-router-dom";
import Home from "./pages/Home.js";
import Course from "./pages/Course.js";
import User from "./pages/User.js";
import NotFound from "./pages/NotFound";
import List from "./pages/List";

class App extends Component {
  render() {
    return (
          <Router>
            <ul>
              <li>
                <Link to="/">Home page</Link>
              </li>
              <li>
                <Link to="/course">course</Link>
              </li>
              <li>
                <Link to="/user">The user</Link>
              </li>
                <li>
                    <Link to="/list">List of pp.</Link>
                </li>
            </ul>{/* Routing configuration */}<Switch>{/ * πŸš€ (1) * /}<Route exact path="/" component={Home} />
                <Route  path="/course" component={Course}/>
                <Route  path="/user" component={User}/>
                <Route  path="/list" component={List}/>
                <Route component={NotFound}/>
              </Switch>
          </Router>); }}export default App;

Copy the code
  • The Link label corresponds to the A label of the HMTL

  • After using the HashRouter tag, the URL path will have #

  • Adding an exact attribute to a Route is an exact match

  • Switch is a Switch. Without a Switch, the NotFound component will be rendered regardless of which path is accessed

  • πŸš€Route should not have Spaces if used with closed tags, because if Spaces are present, a warning will be raised and components in component will not be rendered

    Warning: You should not use <Route component> and <Route children> in the same Route; <Route component> will be ignoredCopy the code

React nested routines are configured and examples:

http://localhost:3000/course/react if this is the form of a url, so how to handle πŸ€”?

The content in πŸš€ App remains unchanged, so start with the Course component:

//Course.js
import React, {Component} from 'react';
import {Route, Link} from "react-router-dom";
import CourseDetail from "./CourseDetail";
import CourseIndex from "./CourseIndex";
class Course extends Component {
    render() {
        return (
            <div>{/*πŸš€ Define a secondary route */}<ul>
                  <li>
                      <Link to="/course/react">The React course</Link>
                  </li>
                  <li>
                      <Link to="/course/vue">Vue course</Link>
                  </li>
                  <li>
                      <Link to="/course/angular">Presents course</Link>
                  </li>
              </ul>{/*πŸš€ Secondary route configuration */}<Route exact path="/course/:courseId" component={CourseDetail}/>
              <Route path={this.props.match.path} component={CourseIndex}/>
            </div>); }}export default Course;
Copy the code
  • ifRouteusecomponentProperties,RouteThere must be no Spaces between labels
  • path="/course/:courseId"There are two main points:
    • coursePreceding the path/Cannot little
    • :courseIdIs a parameter to be passed by the routeReact, Vue, AngularOne of the three
  • this.props.match.pathThe routing becomes dynamic, with values matching the current componentThe path pathHere it is/course

πŸš€ Take a look at the CourseDetail component again

//CouresDetail.js
import React, {Component} from 'react';

class CourseDetail extends Component {
    componentDidMount() {
        console.log("I am course Details".this.props.match.params.courseId)
    }
    render() {
        const {location,match,history}  = this.props;
        // πŸš€ location: local information object
        // πŸš€ match: matches the routing information object
        // πŸš€ history: history object
        console.log(location,match,history);
        return (
            <div>CourseId :{mate.params.courseid}</div>); }}export default CourseDetail;
Copy the code
  • beThe Router tabsAfter the parcel,propsWill increase3Object:
    • location: Local information object
    • match: Matches the routing information object
    • history: Historical object
  • After deconstructing the above three objects, it can be used to pass throughmatch.params.courseIdAccess to theCourse componentsIn theCouresId (React, Vue, Angular)

3. Use of programmatic navigation

Go straight to the code, oh-da, oh-da, oh-da…

// CourseDetail.js

import React, {Component} from 'react';
class CourseDetail extends Component {
    componentDidMount() {
        console.log("I am course Details".this.props.history)
    }
    // This is the arrow function, otherwise need to use bind from constructor
    back = () = >{
         this.props.history.goBack();
    }
    goIndex=() = > {
        // πŸš€ programmatic routing
        this.props.history.push("/");
    }
    goHome=() = >{
        // πŸš€ The version of the passed argument
        this.props.history.push({
            pathname:"/".state: {foo:"bar"}})}render() {
        const {match,location,history} = this.props;
        //πŸš€location: local information object
        //πŸš€match: matches the routing information object
        //πŸš€history: history object
        console.log(location,match,history);
        return (
            <div key={this.props.location.key}>CourseId :{mate.params.courseid}<p>
                    <button onClick={this.back}>Return to the previous level</button>
                    <button onClick={this.goIndex}>Jump to home page</button>
                    <button onClick={this.goHome}>Jump with parameters</button>
                </p>
            </div>); }}export default CourseDetail;
Copy the code

Then look at the state passed to home.js

//Home.js

import React, {Component} from 'react';
class Home extends Component {
    componentDidMount() {
        console.log("I'm in, I'm the state in location.".this.props.location)
    }
    render() {
        return (
            <div>{I'm HOME page. This props. The location. The state? this.props.location.state.foo:""};</div>); }}export default Home;
Copy the code

πŸš€ results are as follows:

4. Use of redirect routing components:

The most common is to call “/” and “/home” to call home.js; Take a look at the modified code:

// App.js

import React, {Component} from 'react';
import {BrowserRouter as Router,Route,Link,Switch,Redirect} from "react-router-dom";
import Home from "./pages/Home.js";
import Course from "./pages/Course.js";
import User from "./pages/User.js";
import NotFound from "./pages/NotFound";
import List from "./pages/List";
class App extends Component {
  render() {
    return (
          <Router>
            <ul>
              <li>
                <Link to="/">Home page</Link>
              </li>
              <li>
                <Link to="/course">course</Link>
              </li>
              <li>
                <Link to="/user">The user</Link>
              </li>
                <li>
                    <Link to="/list">List of pp.</Link>
                </li>
            </ul>{/* Routing configuration */}<Switch>{/ * πŸš€ (1) * /}<Route exact path="/home" component={Home} />
                <Route  path="/course" component={Course}/>
                <Route  path="/user" component={User}/>
                <Route  path="/list" component={List}/>{/* πŸš€ is placed in front of NotFound, because the Switch has found the component that matches the condition, it does not proceed further */}<Redirect to="/home"/>
                <Route component={NotFound}/>
              </Switch>
          </Router>); }}export default App;
Copy the code

5. Display of route query parameters:

Similar to HTTP: localhost: 3000 / user? How is id=3 obtained in routing? What about the ID part?

Take the User component as an example. The code is as follows:

//User.js

import React, {Component} from 'react';
//http:localhost:3000/user? userId=3
import {Link} from "react-router-dom";

function ShowUser({id}){
    return (
        <div>Current user :{id}</div>)}class User extends Component {
    render() {
      // πŸš€ where URLSearchParams is used to store query keys and value pairs
        const params = new URLSearchParams(this.props.location.search);
        console.log(params);
        return (
            <div>
                <ul>
                    <li><Link to={{pathname:'/user',search:"?id=1}} ">User 1</Link></li>
                    <li><Link to={{pathname:'/user',search:"?id=2}} ">The user 2</Link></li>
                    <li><Link to={{pathname:'/user',search:"?id=3}} ">The user 3</Link></li>
                </ul>
                <ShowUser id={params.get("id")} / >
            </div>); }}export default User;
Copy the code

URLSearchParams is used to store the query parameter ID. If multiple parameters are involved, you can also use the for… For more operations, see the following address:

Developer.mozilla.org/zh-CN/docs/…