1.React Describes how to use routes

version

React-router-dom is now available in version 6.0 and is currently unstable.

Using the step

  1. The installation package. NPM I [email protected]

    This package provides three core components :HashRouter(BrowserRouter), Route, and Link

  2. Import the package and use it. import { HashRouter, Route, Link } from ‘react-router-dom’

    With a HashRouter wrapped around the entire application, there is only one Router in a project

  3. Use Link to specify navigation links

  4. Use Route to specify routing rules (which path shows which component

import React from 'react'
import ReactDom from 'react-dom'
import { HashRouter, Route, Link } from 'react-router-dom'
import Search from './pages/Search.jsx'
import Comment from './pages/Comment.jsx'
export default function App () {
  return (
    <div>
      <h1>React Routes are used basically</h1>
      <HashRouter>
        <Link to="/comment">comments</Link>
        <Link to="/search">search</Link>

        <Route path="/comment" component={Comment} />
        <Route path="/search" component={Search} />
      </HashRouter>
    </div>
  )
}
ReactDom.render(<App />.document.getElementById('root'))
Copy the code

2. Route object -Router

1.Router has two modes

HashRouter: hash pattern

BrowserRouter: history model

2. Internal mechanism of the Router

The Router component: wraps the entire application. A React application only needs to be used once

Two commonly used routers are HashRouter and BrowserRouter

  • HashRouter: Implemented using the hash value of the URL

    • Principle: Listen on WindowshashchangeEvent to implement
  • BrowserRouter: Implemented using H5’s history.pushState() API

    • Principle: Listen on WindowspopstateEvent to implement

3. General usage

Use es6 import renaming to unify the name: Whichever route object you import is called Router

import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import { HashRouter as Router, Route, Link } from 'react-router-dom'
Copy the code

3. Route objects Link and NavLink– declarative navigation

Import {Link, NavLink} from ‘react-router-dom’ import {Link, NavLink} from ‘react-router-dom’

1.Link

The Link component cannot show which Link is in the selected effect \

<Link to="/search"> search < / Link >Copy the code

2.NavLink

The NavLink component, a more specialized Link component, can be used to specify the current navigation highlighting

Format:

<NavLink to="/xxx" activeClassName="active"> link < / NavLink >Copy the code

Description:

  • The to attribute, which specifies the address, is rendered as the href attribute of the A tag
  • ActiveClassName: Used to specify the highlighted class name, defaultactive. Generally not to modify
  return (
    <div>
      <h1>React Routes use -link</h1>
      <Router>
        <div>
          Link:
          <Link to="/search">search</Link>
          <Link to="/comment">comments</Link>
        </div>
        <div>NavLink: Comes with highlighting classes<NavLink to="/" exact>The home page</NavLink>
          <NavLink to="/search">search</NavLink>
          <NavLink to="/comment">comments</NavLink>
        </div>
        <Route path="/comment" component={Comment} />
        <Route path="/search" component={Search} />
      </Router>
    </div>
  )
Copy the code

4. Route object Route

The function and format of route

  1. Function: Determines the route matching rule
  2. Format:<Route path="/xx/xx" Component ={component}></Route>

1. Matching rules

Noun agreement:

  1. Path: The value of the path property in the Route component

  2. Pathname: indicates the following format

    1. The value of the to property in the link component
    2. Address in the address bar

Fuzzy matching rule

  1. A match is successful as long as the pathName starts with path
  2. If the match is successful, load the corresponding component.
  3. The whole matching process is matched one by one. Once a match is successful, the match will not stop.

Fuzzy matching and exact matching

  1. The default is fuzzy matching!!
  2. Complementary exact can be set to exact match
import React from 'react'
import ReactDom from 'react-dom'
import { BrowserRouter as Router, Route, NavLink } from 'react-router-dom'
const Home = () = > <div>The home page</div>
const Article = () = > <div>Article list page</div>
const ArticleDetail = () = > <div>Article Details page</div>
export default function App () {
  return (
    <div>
      <h1>React Routes are used basically</h1>
      <Router>/ / navigation<NavLink to="/">The home page</NavLink>&nbsp;
        <NavLink to="/article">Article list page</NavLink>&nbsp;
        <NavLink to="/article/123">Article details page -123</NavLink>&nbsp;
        <hr />// Corresponding jump rule<Route path="/" component={Home} />
        <Route path="/article" component={Article} />
        <Route path="/article/123" component={ArticleDetail} />
      </Router>
    </div>
  )
}
ReactDom.render(<App />.document.getElementById('root'))
Copy the code

2. Exact match

If you do not specify exact matching, all names starting with ‘/’ will be matched with exact matching. For example, ‘/home’, ‘/login’ and exact matching will be matched only when path is set to ‘/’

<Route path="/" exact component={Home} />
Copy the code

5.Switch

1. Usage:

Wrap multiple Route components with Switch components.

Under the Switch component, no matter how many routes match the routing rule, only the first matching component is rendered

import React from 'react'
import ReactDom from 'react-dom'
import {
  BrowserRouter as Router,
  Route,
  NavLink,
  Switch
} from 'react-router-dom'
const Home = () = > <div>The home page</div>
const Article = () = > <div>Article list page</div>
const ArticleDetail = () = > <div>Article Details page</div>
export default function App () {
  return (
    <div>
      <h1>React Routes are used basically</h1>
      <Router>
        <NavLink to="/">The home page</NavLink>&nbsp;
        <NavLink to="/article">Article list page</NavLink>&nbsp;
        <NavLink to="/article/123">Article details page -123</NavLink>&nbsp;
        <hr />
        
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/article" component={Article} />
          <Route path="/article/123" component={ArticleDetail} />
        </Switch>
      </Router>
    </div>
  )
}
ReactDom.render(<App />.document.getElementById('root'))
Copy the code

2. 404 page processing

The 404 error page prompt is very easy to implement with the Switch component

Without setting the path attribute, place the route corresponding to page 404 in the last position inside the switch

       <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/article" component={Article} />
          <Route path="/article/123" component={ArticleDetail} />
          <Route component={Page404} />
       </Switch>
Copy the code

6. Page redirection

The following code:

After matching from = ‘/’, redirect to the component corresponding to the “/comment” path where the FROM page can be rewritten as path

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

<Redirect from="/" exact  to="/comment"  />
Copy the code

7. React-router programmatic navigation

1. The history object

Use format:

import {useHistory} from 'react-router-dom'

export default function App() {
  const history = useHistory()
  // Jump to the specified page
  history.push('/home')
  
  // The n parameter indicates the number of pages to move forward or back (e.g. -1 to move back to the previous page)
  history.go(-1) 
  
  // Replace the current page to display the specified page
  history.replace('/login')}Copy the code

2. The difference between history.replace and push

Push: Adds an entry to history

Replace: Replaces the current record with the target record in history

The sample

push:

Details page --> Login page (push) ----> home pageCopy the code

At this point, stepping back from the home page returns you to the Login page. replace

Details page --> login page (replace) ----> home pageCopy the code

At this point, stepping back from the home page returns you to the details page.

8. Route forward parameters are transmitted

1. The location object

I prefer to use the location object and the state and search methods to get the routing value. Let’s take a look at the location:

How do you get it in a componentlocationObject:

1. The props object in this component contains a location:

export default function Article (props) {
  console.log('props objects', props) 
  return (
        <div>
            Article
        </div>)}Copy the code

The printed result is shown as follows:

2. History also contains a location object

import { useHistory } from 'react-router-dom'
export default function Article () {
  const history = useHistory()
  console.log(history)
  return (
        <div>
            Article
        </div>)}Copy the code

The printed result is shown as follows:

3. UseLocation Hook obtain

import { useLocation } from 'react-router-dom'
export default function Article () {
  const location = useLocation()
  console.log('Location obtained using useLocation', location)
  return (
        <div>
            Article
        </div>)}Copy the code

The printed result is shown as follows:

2. Parameter transfer of declarative navigation:

2.1. Query Parameter methods:

<Link to= '/home/article ? id=9 '> Content management </Link>Copy the code

2.2. Object Writing:

// Pass a single id (location.id)
<Link to={{ pathname: '/home/article'.id: 3Content management </Link>// Pass id and name (location.state)
// If it is not state:{parameter to pass}, the original state property of location will be overridden
<Link to={{ pathname: '/home/article', state: {id:3 , name:'Give me onediv'} }}>Content management</Link>

Copy the code

2.3. Receiving Data:

Select * from location; select * from location;

2. Object writing

2.4. The values:

const value = location.state

const value = location.search

3. Parameter transfer for programmatic navigation

Location,search,state again

   message.success('Login successful'.2.() = > {
      // Jump to the home page
        history.replace('/home? id=33')})Copy the code

Const value = location.search // result:? Id =33 and I need to intercept that

  message.success('Login successful'.2.() = > {
      // Jump to the home page
        history.replace('/home'.'Give me a div.')})Copy the code

Const value = location.state // Result: Give me a div

  message.success('Login successful'.2.() = > {
      // Jump to the home page
        history.replace('/home', { name: 'Give me a div.'.id: 9})})Copy the code

Const value = location.state // {name: ‘Give me a div’, id: 9}

4. Route Transmission Value summary:

Personally, I prefer this way to pass parameters. When jumping, I directly give parameters, and all parameters are received in location, and the way to get location is also very convenient Use the useParams hook to pass parameters to functions. If the match object for props is a params object, use the useParams hook