When I first learned React, I didn’t understand how to use the React route. This time I finally figured it out myself. This article introduces the functions of common routing components, routing component parameter passing, and programmatic navigation.
To make a long story short, the React Web application uses the Web version of the React router, that is, the react router-dom. Note that if the project is created using the create-react-app scaffolding, you will need to install the React-router-dom separately.
React-router-dom exposes some components that implement route switching, which we will also learn about.
React use case version: V17.0.2
Link, Route, BrowserRouter
Route switching can be done using these three components. Here are some examples:
import {Link, Route, BrowserRouter} from 'react-router-dom'
<BrowserRouter>
<Link to="/home">home</Link>
<Link to="/about">about</Link>
<Route path='/home'> <Home/> </Route>
<Route path='/about'> <About/> </Route>
</BrowserRouter>
Copy the code
Link component, equivalent to a tag, is actually rendered as a tag on the page, its function is to switch routes, when clicked, will activate the corresponding routing path, its to attribute is to mark the routing path.
is familiar to those who have used Vue.
The Route component registers the Route, the path property matches the current routing path, and the Component property passes in the component that matches the current path. When path matches, it renders the component passed in by The Component.
You can also write the component to be rendered directly in the component tag as follows:
<Route path='/home'> <Home/> </Route>
<Route path='/about'> <About/> </Route>
Copy the code
Adding exact Enables strict matching. That is, path matches only when it is the same as to in Link.
The BrowserRouter component, for some reason, uses a BrowserRouter wrapper on the outermost layer of the routing application.
It would be more accurate to wrap the mapped Link and Route in the same BrowserRouter, so it would be wrong to wrap them separately:
<BrowserRouter>
<Link to="/home">home</Link>
<Link to="/about">about</Link>
</BrowserRouter>
<BrowserRouter>
<Route path='/home' component={Home}></Route>
<Route path='/about' component={About}></Route>
</BrowserRouter>
Copy the code
Using BrowserRouter packages separately will not match the corresponding components. Sometimes you can apply the BrowserRouter component to an entry file for convenience, as follows:
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>.document.getElementById('root'));Copy the code
This eliminates the need to include BrowserRouter in your component and allows you to write links and routes wherever you want.
In practice, you don’t want to write them all together, as we did in the first example. Just remember that the Link and Route that match each other are on the same BrowserRouter.
HashRouter
It does the same thing as BrowserRouter, except it goes from a history route to a hash route.
Just like vue-Router, SPA applications have both routing modes. The principle is not explained here. There are many articles in the community.
NavLink
The effect is the same as Link, but when the route is activated, the rendered A tag will add the name of the active class. The advantage of this is that you can define the style of the route activation, only need to define the style of the active class.
The activeClassName attribute can be used to customize the activeClassName of the activeClassName class:
<NavLink activeClassName="selected" to="/about">about</NavLink>
<NavLink activeClassName="selected" to="/home">home</NavLink>
Copy the code
The final dom element is rendered with the class name
Switch
The Switch component is used to wrap a Route, which can improve the efficiency of Route matching. When a Route matches a Route, it will continue to match the Route even if it is matched. For example:
<Route path='/home' component={Home}></Route>
<Route path='/home' component={Test}></Route>
Copy the code
In the code above, both routes match a path of /home, and the home and Test components are rendered to the page.
If there are many routes, the match will continue until the end, which obviously affects the efficiency.
If you want to avoid this, you can use a Switch wrap, which is a single route match and ends when it is matched.
<Switch>
<Route path='/home' component={Home}></Route>
<Route path='/home' component={Test}></Route>
</Switch>
Copy the code
At this point, the Test component will no longer match.
Redirect
Redirection component that redirects to a specified route after matching a rule.
Redirect when used with switches, you can Redirect at the back of the Redirect, i.e. when all of the above routes do not match, you can Redirect at the back.
<Switch>
<Route path='/home' component={Home}></Route>
<Route path='/about' component={About}></Route>
// If neither match, redirect to /home
<Redirect to="/home" />
</Switch>
Copy the code
When used directly on a component, redirection is triggered when the component renders:
import React, { Component } from 'react'
import { Redirect } from 'react-router-dom'
export default class Test extends Component {
render() {
return (
<div>The Test component, which I'll redirect to /about when I render<Redirect to='/about' />
</div>)}}Copy the code
Pass parameters to the routing component
There are three common ways to pass parameters to a routing component:
1. Pass the params parameter
Parameter values are concatenated directly on the routing link, for example to pass the article ID parameter to the article page:
// 123 is the id of the article to pass
<Link to='/article/123'></Link>
Copy the code
The routing component needs to declare the receive ID parameter:
<Route path='/article/:id' component={Article}/>
Copy the code
Then get the parameters inside the component:
// Get the params argument passed in
this.props.match.params // {id: '123'}
Copy the code
2. Pass the search parameter
Parameter values are also concatenated to the route link, but need to be used in the way of query, that is, add? Prefix, as in the previous example, search:
<Link to='/article? id=123'></Link>
Copy the code
The routing component does not need to declare the receive ID parameter:
<Route path='/article' component={Article} />
Copy the code
Component internal fetch parameters:
// Get the search argument
this.props.location.search / /? id=123
Copy the code
You can use the query-String library to format the parameters:
import querystring from 'query-string'
querystring.parse(this.props.location.search) // {id:'123'}
Copy the code
3. Pass the state parameter
Parameter values need to be passed as objects:
<Link to={{pathname:'/article'.state: {id:123}}}></Link>
Copy the code
The routing component also does not need to declare the receive ID parameter:
<Route path='/article' component={Article} />
Copy the code
Component parameters:
// Get the state argument
this.props.location.state // {id: '123'}
Copy the code
Note: If BrowserRouter is enabled, the status will not disappear, but if HashRouter is used, the status will disappear.
Programmatic routing navigation
React uses programmatic navigation, which makes use of the push, replace, Go, goBack, and goForward apis in the History object of the props property in the routing component.
This.props.history. Push (‘/home’) is easy to use and won’t be expanded here.
withRouter
Only the props of routing components have routing parameters to perform programmatic navigation. Non-routing components cannot perform programmatic navigation directly.
For example, app.js in the React application is usually the home page entry, which is opened by entering the address in the browser rather than jumping to the Route. Therefore, it cannot be navigated programmatically. Its this.props is empty.
The withRouter is used to pass the history, location, and match parameters to the props of the component.
import React, { Component } from "react";
import { Route, withRouter } from "react-router-dom";
import Message from "./pages/Message";
import Home from "./pages/Home";
class App extends Component {
render() {
console.log(this.props); // Route parameters are available on props only if wrapped by withRouter
return (
<div className="App">
<Route path="/message" component={Message}></Route>
<Route path="/home" component={Home}></Route>
</div>); }}export default withRouter(App); // Just wrap it here
Copy the code
At the end
Please point out any mistakes.