“This is the 14th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”
preface
React is an MVVM framework, and the routing function is essential. When we use Vue Router, some of the most commonly used functions are the rendering of the routing page, adding the content of the routing page, configuring the routing address, routing redirection, routing parameter transmission, and embedded routing routes, etc. In this article, we’ll find out how these common functions are implemented in the React Router to get you started with React Router5.0.
In the previous article, I introduced how to render the routing page, how to set the content of the routing page, and how to set the routing address. This article will continue to introduce how to jump the route, how to receive the parameters of the route, and how to lazy load the route.
I. How to jump a route
There are two ways to route jump in Vue Router, one is declarative, the other is programing.
declarative | programmatic |
---|---|
<router-link :to="..." > |
router.push(...) |
Does the React Router also have declarative and programmatic routing hops? Take an example to introduce, for example: implement a click on the first page to jump to the second page, click on the second page to jump to the first page.
1.1 Declarative route hops
Use the Link component to implement the jump. The to property sets the Route address to jump to. Remember that the Link component must be used within the Route component.
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter, Route ,Link} from "react-router-dom"; ReactDOM.render( <div> <BrowserRouter> <Route path="/one" render={() => { return ( <div><Link To = "/ two" > go to the second page < / Link > < / div >)}} > < / Route > < the Route path = "/ two" render = {() = > {return (< div > < Link To = "/ one" > go to the first page < / Link > < / div >)}} > < / Route > < / BrowserRouter > < / div >, the document. The getElementById (" root "));Copy the code
1.2 Programmatic route hops
The usage is different in class components and function components, which are described separately.
1.2.1 Programmatic route hops in function components
Use the useHistory() Hook to get the history, and then call history.push(path) to jump the route.
A programmatic route jump in a 1.2.2 class component
Retrieve history from the class component using props and call history.push(path).
Concrete implementation see the following demo.
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter, Route, useHistory } from "react-router-dom"; class OnePage extends React.Component { constructor(props) { super(props) const { history } = this.props; this.history = history; this.jump = this.jump.bind(this) } jump = () => { this.history.push('/two') } render() { return ( <div> <div < span style = "box-sizing: border-box; color: RGB (74, 74, 74); font-size: 13px! Important; white-space: inherit! Important;" const handleClick = () => { history.push("/one"); } return (<div onClick={handleClick}> to the first page </div>)} reactdom.render (<div> <BrowserRouter> <Route path="/one") component={OnePage} > </Route> <Route path="/two" component={TwoPage} ></Route> </BrowserRouter> </div>, document.getElementById('root') );Copy the code
How to receive route parameters
The practice of receiving routing parameters in a class component is different from that in a function component and will be discussed separately. In addition, each type of receiving route parameter transmission corresponds to a route parameter transmission method, which is consistent in class component and function component, and will be intersperated in each type of receiving route parameter transmission method.
2.1 Receiving route transmission parameters in function components
There are three hooks (useLocation, useParams, and useRouteMatch) in the function component that can receive route parameters. The following describes how to use each Hook.
2.1.1 useLocation
const location = useLocation();
console.log(location)
Copy the code
To see the result, execute the useLocation in the function component and print the result, look like this:
Focus on the search and state attributes in the result, which are used to receive route parameters.
So how do you pass the parameters to the route that you receive from the search and state of the object that the useLocation returns? As you can see in the previous section, there are two kinds of hops in a route, one is declarative, the other is programmatic.
Search Indicates the request parameters for receiving the redirect address. For example, /one? If id=1, search =? Id =1, which can be passed in a declarative jump.
Push (‘/one’,{name:’ first page ‘})). This is usually passed in a programatically jump.
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter, Route, Link, useLocation, useHistory } from "react-router-dom"; const OnePage = () =>{ const location = useLocation(); Console. log(' first page ',location) return (<div><Link to="/two? Id =2"> </div>)} const TwoPage= () =>{const location = useLocation(); Console. log(' second page ',location) const history = useHistory(); From '/one',{name:' first page '})} return (<div onClick={toOnePage}> go to first page </div>)} ReactDOM.render( <div> <BrowserRouter> <Route path="/one" component={OnePage} > </Route> <Route path="/two" component={TwoPage} ></Route> </BrowserRouter> </div>, document.getElementById('root') );Copy the code
From both OnePage and TwoPage components, the result of useLocation() execution is printed as shown below:
When history.push(‘/one’,{name:’ first page ‘}) is used to jump to the first page, the value of state in the result of the useLocation() is {name: “first page “}.
When using Id = 2 “.
2.1.2 useParams
UseParams Indicates the path parameter for receiving the jump address. For example, /one/1, where 1 is the path parameter.
The path parameter can be received with useParams only after the path attribute of the Route component has been added in a specific way.
For example, if path is set to /one/: ID /:num and the hop address of the route is /one/2/3/4, useParams receives {ID :2,num:3}.
Click on the first page to jump to the second page, click on the second page to jump to the first page, pay attention to the value of the path attribute of the Route component, Route jump address and the result of useParams() executed in each component.
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter, Route, Link, useHistory, useParams } from "react-router-dom"; const OnePage = () =>{ const params = useParams(); Console. log(' first page ',params); Return (<div><Link to="/two/2/3">)} const TwoPage= () =>{const params = useParams(); Console. log(' second page ',params); const history = useHistory(); From '/one/1/3')} return (<div onClick={toOnePage}> go to the first page </div>)} reactdom.render ( <div> <BrowserRouter> <Route path="/one/:id/:num" component={OnePage} > </Route> <Route path="/two/:id" component={TwoPage} ></Route> </BrowserRouter> </div>, document.getElementById('root') );Copy the code
Print the results of useParams() executed in each component in the demo above, as shown in the figure below:
Also be careful if you set a Route componentpath
The URL that accesses the Route component must also have several path parameters, otherwise it cannot be accessed.
2.1.3 useRouteMatch
Run useRouteMatch() to get the routing data for the current routing page. The data has a params field with the same value as the data obtained by executing useParams().
If useRouteMatch is used to obtain Route parameters, it is necessary to add a path to the path attribute of the Route component in a specific way before useRouteMatch can receive the path parameters.
For example, if the path of the Route component rendering the first page is set to /one/:id/:num and the hop address is /one/2/3/4, then run useRouteMatch() in the first page Route component,
import { useRouteMatch } from "react-router-dom"; const OnePage = () =>{ const match = useRouteMatch(); console.log(match); Return (<div> first page </div>)}Copy the code
The routing data match on the current routing page can be obtained as follows:
The red box is the route parameter. Is it the same as useParams()?
2.2 Receiving route transmission parameters in class components
Get location and match from the class component using props, and then get the route parameters search (request parameter), params (path parameter), and state from there.
Print the props in the “first page” routing page component.
class OnePage extends React.Component { constructor(props) { super(props) console.log(this.props) } render() { return ( <div> <div> the first page </div> </div>)}}Copy the code
The print result is as shown in the figure below:
The route parameters search, params, and state are passed in the previous section of receiving route parameters in a function component.
3. Routes are loaded lazily
Use React. Lazy to define a dynamically loaded component for lazy route loading.
Note: Components defined in React. Lazy must be packaged for use in
, and the React. Girl property fallback is required.
For example, to lazily load the OnePage routing page component, the implementation code looks like this:
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter, Route, } from "react-router-dom"; const OnePage = React.lazy(() => import('./OnePage')); Const Spinner = () => {return (<div>); </div> ) } ReactDOM.render( <div> <React.Suspense fallback={<Spinner/>}> <BrowserRouter> <Route path="/" component={OnePage} > </Route> </BrowserRouter> </React.Suspense> </div>, document.getElementById('root') );Copy the code