Five minutes to teach you about react routing

  • 2021-11-24 00:52:46
  • OfStack

Directory What Is Routing Basic use of pure components Points for Attention in Pure Component Use Basic Initial Experience of Routing HashRouter and BrowserRouter Link component and NavLink component Route and Switch components Routing parameter transfer

What is a route

Simply put, according to different addresses, web server handles different services and logic.

The following code all runs in an react scaffold

Basic use of pure components


//  Component update mechanism :
//  As long as the parent component is rendered again ,  All component subtrees ,  Will also be updated 

//  Performance optimization 
// 1.  Mitigate state

// 2.  Avoid unnecessary re-rendering  ( Performance optimization )
//    shouldComponentUpdate(nextProps, nextState) { .... }
//     Hook function returns 1 Boolean values , true To update  false Do not update 
//     Manual implementation is certainly possible ,  But it's too much trouble 

// 3.  The actual official website provides 1 Pure components ,  The interior has already helped you realize it  shouldComponentUpdate  Logic of 
//     Will help you carry out props  And  state Comparison of ,  Decide whether to update 
//     Common component : class App extends React.Component
//     Pure component :   class App extends React.PureComponent   Will be better than ordinary components ,  More 1 The process of comparing data 

//     For example : 1 Components to render ,  The performance loss is very large ,  Consider pure components at this point ,  Avoid dropping 1 Some meaningless updates 
//     Not all the scenes ,  Use pure components ,  Normal components should be used 

import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.PureComponent {
  state = {
    nameList: [' Shuai Peng ', ' Lyu3 bu4 ', ' Zhang Fei '],
    currentName: '',
  }
  render() {
    console.log('App-render')
    return (
      <div>
        <h1> I am App Component </h1>
        <h3> Results : {this.state.currentName}</h3>
        <button onClick={this.handleClick.bind(this)}> Roll call </button>
      </div>
    )
  }
  handleClick() {
    const randomIndex = parseInt(Math.random() * this.state.nameList.length)
    const currentName = this.state.nameList[randomIndex]

    this.setState({
      currentName,
    })
    console.log(currentName)
  }

  //  Demand :  If state Value of ,  There has been no change ,  In fact, there is no need to update ,  Avoid 1 Some unnecessary updates 
  // shouldComponentUpdate(nextProps, nextState) {
  //   if (this.state.currentName === nextState.currentName) {
  //     return false
  //   } else {
  //     return true
  //   }
  // }
}
ReactDOM.render(<App></App>, document.getElementById('root'))

Points for Attention in Pure Component Use


// 4.  Points for Attention in the Use of Pure Components   ( If a pure component has child components ,  Subcomponents should also be pure components  (1 All families are pure ))
// (1)  Shallow contrast is carried out inside pure components ,  There is nothing wrong with the value type ,  Complex types compare addresses only 
// (2)  Use pure components ,  When updating data ,  There is no problem with simple types ,  Complex types have been updated ,  The address needs to be modified ( New object  /  New Array )

import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.PureComponent {
  state = {
    nameList: [' Shuai Peng ', ' Lyu3 bu4 ', ' Zhang Fei '],
    currentName: '',
    obj: {
      name: 'zs',
      age: 18,
    },
  }
  render() {
    console.log('App-render')
    return (
      <div>
        <h1> I am App Component </h1>
        <p>name: {this.state.obj.name}</p>
        <p>{this.state.nameList}</p>
        <button onClick={this.handleClick.bind(this)}> Value modification </button>
      </div>
    )
  }
  handleClick() {
    //  To update an object ,  Be prepared 1 New objects 
    // const obj = { ...this.state.obj }
    // obj.name = 'ls'
    // this.setState({
    //   obj: obj,
    // })
    //  To update an array ,  Be prepared 1 New arrays 
    // this.setState({
    //   nameList: [...this.state.nameList, ' Wang 5'],
    // })
    const arr = [...this.state.nameList]
    arr.push(' Wang 5')
    this.setState({
      nameList: arr,
    })
  }
}
ReactDOM.render(<App></App>, document.getElementById('root'))

Basic Initial Experience of Routing


import React from 'react'
import ReactDOM from 'react-dom'
import { HashRouter, Link, Route } from 'react-router-dom'

//  Use of routing :
// 1.  Download  yarn add react-router-dom
// 2. react-router-dom Yes 1 Package ,  It contains many components 
// 3. HashRouter Component ,  Is the entire routing object , 1 One project is 1 A ,  You need to wrap the contents of the whole project 
// 4. Link Component ,  Render into 1 A  a  Link ,  Can be used for routing jumps ,  Pass  to  Configuration path 
// 5. Route Component ,  Configure routing rules ( Which path matches which component ),  It is also a routing exit !
//     Each Route They are independent of each other ,  As long as the path matches ,  You can show the configured components 

//  Defines the 3 Functional components 
const Home = () => <div> I am Home Component </div>
const Login = () => <div> I am Login Component </div>
const User = () => <div> I am User Component </div>

class App extends React.PureComponent {
  render() {
    return (
      <div>
        <h1> I am App Component </h1>
        <ul>
          <li>
            <Link to="/home"> Home page </Link>
          </li>
          <li>
            <Link to="/login"> Login </Link>
          </li>
          <li>
            <Link to="/user"> Users </Link>
          </li>
        </ul>

        {/*  As long as path Path ,  Matches the path of the address bar ,  The configured components are displayed  */}
        <Route path="/home" component={Home}></Route>
        <Route path="/login" component={Login}></Route>
        <Route path="/user" component={User}></Route>
      </div>
    )
  }
}
ReactDOM.render(
  <HashRouter>
    <App></App>
  </HashRouter>,
  document.getElementById('root')
)

HashRouter and BrowserRouter


import React from 'react'
import ReactDOM from 'react-dom'
import { HashRouter as Router, Link, Route } from 'react-router-dom'

// Router Component ,  There are two kinds  HashRouter, BrowserRouter
// 1. HashRouter The underlying implementation is based on :  Address bar hash Value ,  Based on anchor jump 
// 2. BrowserRouter The underlying implementation is based on : h5  Adj.  history API,  There is no address bar  #
//   ( If you want to use the development time ,  No problem ,  But it's online ,  Background configuration is required )

//  Defines the 3 Functional components 
const Home = () => <div> I am Home Component </div>
const Login = () => <div> I am Login Component </div>
const User = () => <div> I am User Component </div>

class App extends React.PureComponent {
  render() {
    return (
      <div>
        <h1> I am App Component </h1>
        <ul>
          <li>
            <Link to="/home"> Home page </Link>
          </li>
          <li>
            <Link to="/login"> Login </Link>
          </li>
          <li>
            <Link to="/user"> Users </Link>
          </li>
        </ul>

        {/*  As long as path Path ,  Matches the path of the address bar ,  The configured components are displayed  */}
        <Route path="/home" component={Home}></Route>
        <Route path="/login" component={Login}></Route>
        <Route path="/user" component={User}></Route>
      </div>
    )
  }
}
ReactDOM.render(
  <Router>
    <App></App>
  </Router>,
  document.getElementById('root')
)

Link component and NavLink component


import React from 'react'
import ReactDOM from 'react-dom'
import { HashRouter as Router, NavLink, Route } from 'react-router-dom'
import './index.css'

// Link Component   And  NavLink Component 
// 1. Link Component ,  Render into a Link ,  Used for routing jumps ,  Pass to Configuration path 
//     Default Link,  There will be no highlighted class name identification 
// 2. NavLink Component ,  Render into a Link ,  Used for routing jumps ,  Pass to Configuration path 
//    (1) NavLink,  When the path matches, ,  There will be a highlighted class name  active
//    (2)  It can be passed through activeClassName,  Configure highlighted class names 
//    (3)  It can be passed through activeStyle,  Directly configure and change labels ,  Highlighted style 
//    (4)  Fuzzy matching is carried out   to="/home"  Can be matched   /home  /home/aa
//         Exact matching ,  Requires configuration  exact  Attribute ,  to="/home",  Match only  /home,  Will only be in  /home  Time highlight 

//  Defines the 3 Functional components 
const Home = () => <div> I am Home Component </div>
const Login = () => <div> I am Login Component </div>
const User = () => <div> I am User Component </div>

class App extends React.PureComponent {
  render() {
    return (
      <div>
        <h1> I am App Component </h1>
        <ul>
          <li>
            <NavLink
              exact
              to="/"
              activeStyle={{ color: 'red', fontSize: '30px' }}
            >
               Home page 
            </NavLink>
          </li>
          <li>
            <NavLink to="/login" activeClassName="selected">
               Login 
            </NavLink>
          </li>
          <li>
            <NavLink to="/user" activeClassName="selected">
               Users 
            </NavLink>
          </li>
        </ul>

        {/*  As long as path Path ,  Matches the path of the address bar ,  The configured components are displayed  */}
        <Route path="/home" component={Home}></Route>
        <Route path="/login" component={Login}></Route>
        <Route path="/user" component={User}></Route>
      </div>
    )
  }
}
ReactDOM.render(
  <Router>
    <App></App>
  </Router>,
  document.getElementById('root')
)


/**index.css*/
.active {
  color: red;
  font-size: 30px;
}
.selected {
  color: blue;
  font-size: 30px;
}

Route and Switch components


import React from 'react'
import ReactDOM from 'react-dom'
import { HashRouter as Router, NavLink, Route, Switch } from 'react-router-dom'
import './index.css'

// Route Component 
//  Action :  You can configure routing rules ,  It is also the exit of the route ,  As long as the paths match ,  Then the configured component ,  It will be displayed here 
// <Route path="/login" component={Login}></Route>
// 1.  Each Route Between ,  Are independent of each other  ( Including configuring multiple identical paths ,  Show different components ,  It is also possible )
// 2. Route Configured path ,  It is also a fuzzy matching ,  It can be passed through  exact  Make an exact match 
// 3.  If you do not configure a path ,  Then the configured component ,  Will be displayed by default 
//     Will cooperate Switch Component ,  Can be accomplished 404 Configuration of the page 

// Switch Component :  You can put multiple Route Component package ,  You can make the first 1 Matching Route Component display ,  Follow-up regardless 

//  Function components are defined 
const Home = () => <div> I am Home Component </div>
const Login = () => <div> I am Login Component </div>
const User = () => <div> I am User Component </div>
const Error = () => <div> I am 404 Page ,  The page you are trying to access does not exist !!!</div>

class App extends React.PureComponent {
  render() {
    return (
      <div>
        <h1> I am App Component </h1>
        <ul>
          <li>
            <NavLink
              exact
              to="/"
              activeStyle={{ color: 'red', fontSize: '30px' }}
            >
               Home page 
            </NavLink>
          </li>
          <li>
            <NavLink to="/login" activeClassName="selected">
               Login 
            </NavLink>
          </li>
          <li>
            <NavLink to="/user" activeClassName="selected">
               Users 
            </NavLink>
          </li>
        </ul>

        {/*  As long as path Path ,  Matches the path of the address bar ,  The configured components are displayed  */}
        <Switch>
          <Route path="/" component={Home} exact></Route>
          <Route path="/login" component={Login}></Route>
          <Route path="/user" component={User}></Route>
          <Route component={Error}></Route>
        </Switch>
      </div>
    )
  }
}
ReactDOM.render(
  <Router>
    <App></App>
  </Router>,
  document.getElementById('root')
)

Nested routing


import React from 'react'
import ReactDOM from 'react-dom'
import {
  HashRouter as Router,
  NavLink,
  Route,
  Switch,
  Redirect,
} from 'react-router-dom'
import './index.css'

// Redirect Component :  You can redirect , from From where   to Where to jump 

// react Medium ,  Configuring nested routes ,  Very simple ,  You only need to write nested sub-routes where you need to ,  Direct writing Route Component will do 
//  Precondition ,  The nested sub-routes you configured ,  Path 1 Be sure to include the path of the parent route 

//  Function components are defined 
const Home = () => (
  <div>
    <h3> I am Home Component </h3>
  </div>
)
const Login = () => (
  <div>
    <h3> I am Login Component </h3>
  </div>
)
// ------------------------------------------------------------------------
//  Demand :  Users User Component interior ,  And personal information ,  My collection 
const User = () => (
  <div>
    <h3> I am User Component </h3>
    <Route path="/user" exact component={UserDefault}></Route>
    <Route path="/user/info" component={Info}></Route>
    <Route path="/user/star" component={Star}></Route>
  </div>
)
const UserDefault = () => <div> I am the default User Content </div>
const Info = () => <div> I am Info Component </div>
const Star = () => <div> I am Star Component </div>

// -------------------------------------------------------------------------
const Error = () => <div> I am 404 Page ,  The page you are trying to access does not exist !!!</div>

class App extends React.PureComponent {
  render() {
    return (
      <div>
        <h1> I am App Component </h1>
        <ul>
          <li>
            <NavLink
              exact
              to="/"
              activeStyle={{ color: 'red', fontSize: '30px' }}
            >
               Home page 
            </NavLink>
          </li>
          <li>
            <NavLink to="/login" activeClassName="selected">
               Login 
            </NavLink>
          </li>
          <li>
            <NavLink to="/user" activeClassName="selected">
               Users 
            </NavLink>
          </li>
        </ul>

        {/*  As long as path Path ,  Matches the path of the address bar ,  The configured components are displayed  */}
        <Switch>
          <Route path="/" component={Home} exact></Route>
          <Redirect from="/home" to="/"></Redirect>
          <Route path="/login" component={Login}></Route>
          <Route path="/user" component={User}></Route>
          <Route component={Error}></Route>
        </Switch>
      </div>
    )
  }
}
ReactDOM.render(
  <Router>
    <App></App>
  </Router>,
  document.getElementById('root')
)

Routing parameter transfer


import React from 'react'
import ReactDOM from 'react-dom'
import { HashRouter as Router, Route, Link } from 'react-router-dom'
import './index.css'

//  If you want to get the parameter information of dynamic routing, ,  Need to pass props Get ,
// Route Will route related information ,  Correlation method ,  Will pass  props  Components passed to you 
// const Product = (props) => <div> I am product Component </div>

class Product extends React.Component {
  render() {
    // this.props  Parameter 
    // (1) history   What is stored in it is the method of jumping routing 
    // (2) location   What is stored in it is the current routing address 
    // (3) match  The dynamic routing parameters are stored in it 
    console.log(this.props)
    console.log(this.props.match.params.id)
    return (
      <div>
        <h3> I am product Component  - {this.props.match.params.id}</h3>
        <button onClick={this.handleClick.bind(this)}> Back to the Home Page </button>
      </div>
    )
  }
  handleClick() {
    // console.log(this.props.history)
    // this.props.history.go(-1)
    this.props.history.push('/home')
  }
}

const Home = () => <div> I am the home page </div>

class App extends React.Component {
  render() {
    return (
      <div>
        <h1> I am App Component </h1>
        <div>
          <Link to="/home"> Home page </Link>
          <Link to="/product/1"> Commodity 1</Link>
          <Link to="/product/2"> Commodity 2</Link>
          <Link to="/product/3"> Commodity 3</Link>
          <Link to="/product/4"> Commodity 4</Link>
        </div>
        <Route path="/product/:id" component={Product}></Route>
        <Route path="/home" component={Home}></Route>
      </div>
    )
  }
}
ReactDOM.render(
  <Router>
    <App></App>
  </Router>,
  document.getElementById('root')
)


Related articles: