< a > link jump way
Link and NavLink jump modes
Link is used the same way as NavLink, except that NavLink has the activeClassName attribute, which is used to set the style of the active TAB.
1) index.js entry file file
Since both route hops (Link and NavList) and route registration require a BrowserRouter package, we need to write the BrowserRouter package App component in the entry in order to use the route globally.
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
import "./index.css";
ReactDOM.render(
<BrowserRouter>
<App/>
</BrowserRouter>
,document.getElementById('root'))
Copy the code
2) App component files
import React,{ Component } from "react";
import Main from "./components/Main";
import "./App.css";
export default class App extends Component {
render(){
return (
<div className="app">
<Main></Main>
</div>
)
}
}
Copy the code
3) Main component file
import React,{ Component } from "react"; import NavList from ".. /NavList"; import Center from ".. /Center"; import "./index.css"; export default class Main extends Component { render() { return ( <div className="main"> <NavList ></NavList> <Center ></Center> </div> ) } }Copy the code
4) NavList component file
In this project, we are defining the jump to the route in this file. We are using NavLink where activeClassName=”active” active is our own style, that is, the TAB style of the active route. Route force uses to=”/home”, where /home is the route force to which we want to jump.
import React,{ Component } from "react"; import { NavLink } from "react-router-dom"; import "./index.css"; Export Default class NavList extends Component {render() {return (<div className=" NavList "> <h1>NavList Component </h1> <div className="list-group"> <NavLink activeClassName="active" className="list-group-item " to="/home">Home</NavLink> <NavLink activeClassName="active" className="list-group-item" to="/about">About</NavLink> </div> </div> ) } }Copy the code
5) Center component file
We have written the jump of the route above, but we also need to register the routing table, the project is to write the routing table in this file. The routing table is registered with the Route tag, and the Route uses path=’/home’, where /home is our routing force. Component is the component we need to display for the route jump. The general routing components are written in the Pages directory.
import React,{ Component } from "react"; import { Route } from "react-router-dom"; import Home from ".. /.. /pages/Home"; import About from ".. /.. /pages/About"; import "./index.css"; Export Default Class Center extends Component {render() {return (<div className=" Center "> <h1>Center Component </h1> <Route path='/home' component={Home}></Route> <Route path='/about' component={About}></Route> </div> ) } }Copy the code
Note:
- Routing components can be obtained through
this.props
Obtain routing information. Common components cannot obtain routing information. - Routing components are required to assign to
component
Property instead of writing labels directly. - Routing components are typically written in
pages
directory
Two: NavLink encapsulation
Since NavLink requires some of the same attributes, we can encapsulate it without requiring redundant code every time.
As you can see from the following example, NavLink requires the activeClassName and className common attributes
<NavLink activeClassName="active" className="list-group-item " to="/home">Home</NavLink>
Copy the code
1) MyNavList component file
After wrapping NavLink, the code is as follows:
import React,{ Component } from "react"; import { NavLink } from "react-router-dom"; import "./index.css"; export default class MyNavList extends Component { render() { return ( <NavLink activeClassName="active" className="list-group-item " {... this.props}/> ) } }Copy the code
2) Use MyNavList component
import React,{ Component } from "react"; import MyNavLink from ".. /MyNavLink"; import "./index.css"; Export Default class NavList extends Component {render() {return (<div className=" NavList "> <h1>NavList Component </h1> <div ClassName ="list-group"> {/* redirect */} <MyNavLink to="/home"> </MyNavLink> <MyNavLink to="/about"> </MyNavLink> </div> </div> ) } }Copy the code
Three: Switch usage
When registering a routing table, the Switch label is used. After a specified route is matched, the route is not matched further, which improves efficiency.
import React,{ Component } from "react"; import { Route,Switch } from "react-router-dom"; import Home from ".. /.. /pages/Home"; import About from ".. /.. /pages/About"; import "./index.css"; Export default class Center extends Component {render() {return (<div className=" Center "> <h1>Center Component </h1> {/* With the Switch tag, when the specified route is matched, no further matching is performed. <Route path='/home' component={home}></Route> <Route path='/about' component={about}></Route> </Switch> </div> ) } }Copy the code
Four: Enable fuzzy mode (default) and precise matching (strict matching)
The default is fuzzy matching =false.
Fuzzy matching: The input route must contain the force of the registered route. The input route can be more than the registered route, but the force order must be the same. For example, the registered route is /home, but I input the route strength is /home/a under fuzzy matching, the page is displayed normally, and /b/home/a is not displayed normally.
<Switch> <Route path='/home' component={home}></Route> // Exact path='/about' component={about}></Route> // Strict mode </Switch>Copy the code
Note:
- In general, we do not use strict patterns, but fuzzy matching. Cannot create child routes (route nesting) with strict mode enabled
Five: Route redirection
Redirect is usually placed at the bottom of the routing table. The route /home is turned on by default when we make a typo or enable
<Switch>
<Route path='/home' component={Home}></Route>
<Route exact path='/about' component={About}></Route>
<Redirect to="/home" />
</Switch>
Copy the code
Six: Sub-route
The usage is the same except that child routing tables must contain parent routing tables. In this example, if the parent routing table is /home, the child routing tables are /home/news and /home/news
import React,{ Component } from "react"; import MyNavLink from ".. /.. /components/MyNavLink"; import { Route,Redirect } from "react-router-dom"; import News from "./News"; import Message from "./Message"; import "./index.css" export default class Home extends Component { render() { return ( <div> Home..... <div> <ul className="tab-group"> <li className="tab-group-item"> <MyNavLink to="/home/news"> news </MyNavLink> </li> <li ClassName ="tab-group-item"> <MyNavLink to="/home/message"> message </MyNavLink> </li> </ul> {/* here is a list of child routes */} <Route path="/home/news" component={News}/> <Route path="/home/message" component={Message}/> <Redirect to="/home/news"/> </div> </div> ) } }Copy the code
Seven: Routing transmission parameters
1) Route jump file
import React,{ Component } from "react"; import {Link } from "react-router-dom"; Export Default Class MessageTab extends Component {state = {tabList: [{title: "update ", id: '1'}, {title: "Update on China-India Diplomacy ", id: '2'}, {title:" Update on COVID-19 ", id: '3' } ] } render() { let {tabList} = this.state return ( <ul> { tabList.map(tabItem => { return ( <li key={tabItem.id}> {/ * hop routing, and transfer to the routing component parameter * / params} {/ * < Link to = {` / home/message/TAB / ${tabItem. Id} `} > {tabItem. Title} < / Link > * /} {/ * hop routing, */} {/* <Link to={' /home/message/ TAB /? Id = ${tabItem. Id} `} > {tabItem. Title} < / Link > * /} {/ * hop routing, */} <Link to={{pathName: '/home/message/ TAB',state:{id: tabitem. id}} >{tabitem. title}</Link> </li>)})} </ul> ) } }Copy the code
2) Registration of routing tables
import React,{ Component } from "react"; import {Route } from "react-router-dom"; import MessageTab from "./MessageTab"; import MessageDetail from "./MessageDetail"; Import "./index.css" export default class Message extends Component {render() {return (<div> <MessageTab/> {/* Params {/* <Route path="/home/message/ TAB /:id" component={MessageDetail}/> */} {/* Register Route, */} {/* <Route path="/home/message/ TAB "component={MessageDetail}/> */} {/* Register Route, */} <Route path="/home/message/ TAB "component={MessageDetail}/> </div>)}}Copy the code
3) Routing components receive parameters
import React,{ Component } from "react"; import qs from "querystring"; Export default class MessageDetail extends Component {render() {// let {match:{params:{id}}} = This. Props / * receiving search parameters * / / / let {id} = qs. Parse (this. Props. The location. The search. The substring (1)) / * * / receiving state parameters Console. log(this.props) let {location:{state:{id}}} = this.props return (<div> message details {id} </div>)}}Copy the code
< 2 > Programmatic navigation
In addition to link hops, React-Touter also provides some apis that make it easy to hop routes using JS. Routing table registration, routing component receive parameters and normal link jump are the same.
-
WithRouter.
Encapsulate a common component and return it as a routing component that can use some of the apis provided by routing.
For routing components, we can directly use some of the routing apis, such as the following API:
ƒ go(n) goBack: ƒ go(n) goBack: ƒ goBack() goForward: ƒ goForward() length: 50 listen: ƒ Listen (listener) location: {pathName: "/ home/message/TAB/", search:" ", hash: "", the state: {... ƒ push(path, state) replace: ƒ replace(path, state)}, location: {hash: "key: "yarub9" pathname: "/home/message/tab/" search: "" state: {id: "3"} }, match: { sExact: false params: {} path: "/home/message" url: "/home/message" } }Copy the code
Analysis:
Go: ƒ go (n)
.n
isnumber
Type. A positive number means forwardn
Step, negative number means backn
Step.The goBack: ƒ goBack ()
. Indicates a rollback.GoForward: ƒ goForward ()
. Go forward.Push: ƒ push (path, state)
. Represents pushing, recorded.Replace: ƒ replace (path, state)
. Replaces the current route.
Since the messageTab component is a generic component, to use programmatic routing for navigation, we need to introduce withRouter. Run export default withRouter(MessageTab) to expose it.
import React,{ Component } from "react"; import {withRouter } from "react-router-dom"; Class MessageTab extends Component {state = {tabList: [{title: "us update ", id: '1'}, {title:" US update ", id: '2'}, {title: "Latest outbreak news ", id: '3'}]} showMessageDetail = (tabItem)=> {return ()=> {/* Push mode -- pass params parameter */ // This.props.history.push(' /home/message/ TAB /${tabitem.id} ') /* Push mode -- pass the search argument */ // this.props.history.push(`/home/message/tab/? Id =${tabitem.id} ') /* Pass state */ this.history.push (' /home/message/ TAB/',{id: tabitem.id})} render() { Let {tabList} = this.state return (<ul> {tablist. map(tabItem => {return (<li key={tabitem. id}> {/* Jump route, And transfer to the routing component parameter * / params} {/ * < Link to = {` / home/message/TAB / ${tabItem. Id} `} > {tabItem. Title} < / Link > * /} {/ * hop routing, */} {/* <Link to={' /home/message/ TAB /? Id = ${tabItem. Id} `} > {tabItem. Title} < / Link > * /} {/ * hop routing, And transfer to the routing component state parameters * /} {/ * < Link to = {{the pathname: ` / home/message/TAB `, state: {id: tabItem. Id}}} > {tabItem. Title} < / Link > * /} {/ * Programed navigation */} <div onClick={this.showMessagedetail ({id: tabitem.id})}> {tabitem.title} </div> </li>)})} </ul>)}} export default withRouter(MessageTab)Copy the code
< 3 > BrowserRouter and HashRouter differences
-
- The underlying principle is different:
BrowserRouter
Using theH5
The ` ` ` ` history ` ` ` APIHashRouter
The hash value of the URL is used.
-
- Urls are represented differently:
BrowserRouter
None in the route to#
symbolHashRouter
The route to#
symbol
-
- Refresh the route
state
Influence of parameters:
BrowserRouter
rightstate
The parameters don’t make any difference becausestate
Stored in thehistory
Object, as long as the browser does not clear cached data or closeHashRouter
rightstate
The parameters have any effect,state
Parameters are lost.
- Refresh the route