React-Router
Front-end routing rules
The URL hash
URL
thehash
The anchor point (#) is essentially a changewindow.location
thehref
attribute- We can just assign
location.hash
changeurl
, but the page does not refresh
const routerView1 = document.querySelector('.router-view')
window.addEventListener('hashchange', () = > {switch (window.location.hash) {
case '#/home':
routerView1.innerHTML = 'home';
break; case '#/about': routerView1.innerHTML = 'About page'; break; default: routerView1.innerHTML = ' '; break; } }) Copy the code
Note:
hash
The advantage is better compatibility. In the old version,IE
Can be run- But the drawback is that there is a # that doesn’t look like a real path
It’s history
- The History interface is a new addition to HTML5 and has six modes for changing urls without refreshing the page:
API | role |
---|---|
replaceState | Replace the original path |
pushState | Use a new path |
popState | Path rollback |
go | Change the path forward or backward |
forward | Change the path forward |
back | Change path backwards |
react-router
React-router introduction and installation
- As of React Router version 4, routes are no longer managed in a single package
react-router
Is the core part of the router code;react-router-dom
Is for browsers;react-router-native
Is for native applications;
- At present we use the latest ones
React Router
Version isv5
Version:- In fact
v4
The version andv5
Is not that different;
- In fact
- The installation
react-router
:- The installation
react-router-dom
It will help us install it automaticallyreact-router
Rely on; yarn add react-router-dom
- The installation
Basic use of Router
The main API of the React-Router is the “components” provided to us.
BrowserRouter
orHashRouter
componentRouter
Contains a listen for path changes and passes the corresponding path to the child componentBrowserRouter
Using thehistory
modelHasRouter
Using thehash
model
Link
The component andNavLink
component- In general, the path is used when jumping
Link
, will eventually be rendered asa
The element NavLink
Is in theLink
Added some style properties on top of it (learn later)to
Properties:link
The most important property in a component that sets the path to jump to
- In general, the path is used when jumping
Route
component- “Route Is used to match paths“
path
Property: The path to which the user sets the matchcomponent
Property: Sets the path to match after rendering the componentexact
Attribute: Exact match, only exact match to exactly the same path, will render the corresponding component
// ...
import { BrowserRouter, Link, Route } from 'react-router-dom'
export default class App extends PureComponent {
render() {
return (
<div> <BrowserRouter> <Link to="/"> home </Link><Link to="/about"><Link to="/profile"> my </Link>{/* Add exact attribute: exact match */} <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/profile" component={Profile} /> </BrowserRouter> </div> ) } } Copy the code
Use of NavLink components
- Requirement: “When path is selected, the corresponding A element turns red”
- At this point, we’re going to use
NavLink
Component to replaceLink
componentactiveStyle
: Active (matching) styleactiveClassName
: Added when activecalss
exact
: Whether the match is accurate
{/* The path is selected, the corresponding a element turns red */}
<NavLink exact to="/"
activeClassName="link-active">
The home page</NavLink> <NavLink to="/about" activeStyle={{ color: 'red', fontSize: '35px' }}> about</NavLink> Copy the code
Use the Switch component
- Usage scenario: Just have one
path
Once the corresponding component is matched, there will be no further matches - Let’s look at the following routing rules:
- When we match a certain path, we find some problems
- Such as
/about
When the path matches,/:userid
It was also matched, and the last oneNoMatch
Components are always matched to
- The reason? By default,
react-router
As long as the path is matchedRoute
Corresponding component“Will be rendered“- But in actual development, we want to have an exclusive mindset
- Once you match the first one, there should be no further matches
- We can use it at this point
Switch
To put allRoute
Package components
Redirect to Redirect
- Redirect Redirect is used to Redirect routes. When this component is present, the Redirect is performed
to
In the path
<Redirect to="/login" />
Copy the code
React-router Provides other information
Nesting of routes
Manual routing jumps to withRouter
❝
So far we have implemented the jump is mainly through Link or NavLink to jump, in fact we can also use “JavaScript” code to jump
❞
- To obtain
history
object- Method 1: If the component is“Jump directly through the route“Can be directly from
props
Propertyhistory, location, match
- Method 2: Obtain it from the App component
history
Object that needs to be usedwhitRouter
** Advanced components **App
Components must be wrapped inBrowserRouter
orHashRouter
Within a componentApp
Components usewithRouter
Advanced component packages
- Method 1: If the component is“Jump directly through the route“Can be directly from
// 1. Do not use the Link component or NavLink component to redirect
joinTo() {
// 1. The history used is props passed through the Route component
// 2. Use the history object passed by Route to jump to the path
this.props.history.push('/about/join')
} // app.js jumpToProduct() { this.props.history.push('/product') } Copy the code
Parameter passing
-
“There are three ways to pass parameters:“
- Dynamic routing;
- Search passes parameters;
- The to object is passed in Link
Dynamic routing transmission parameters:
-
For example, if path is written as /detail/:id for Route matching, /detail/ ABC and /detail/123 can match the Route and be displayed
-
graphic
// App.js
<NavLink to={`/detail/${id}`Details} > </NavLink>
<Route path="/detail/:id" component={Detail} />
// Detail.js {/* Get the id parameter of dynamic routing */}<h2>Detail: {match.params.id}</h2> Copy the code
Search transfer parameter
-
The Query String is passed in the Link or NavLink component via the TO attribute
-
graphic
The to attribute in Link can be passed directly to an object
// app.js
<NavLink
to={{
pathname: "/detail".search: "? name=abc".state: info}} > Enter details </NavLink>// detail.js
console.log(this.props.location)
Copy the code
react-router-config
React-router-config Basic configuration
Currently all of our Route definitions are done directly using the Route component and adding attributes, but this approach can become very confusing
- All routing configurations are centrally managed in one place
- Use:
react-router-config
To complete the
- Use:
- The installation
react-router-config
yarn add react-router-config
- Configure the route mapping array
const routes = [
{ path: '/'.component: Home, exact: true },
{ path: '/profile'.component: Profile },
{ path: '/detail/:id'.component: Detail },
]
// app.js
import { renderRoutes } from 'react-router-config'
import routes from './router'
render() {
// ...
{ renderRoutes(routes) }
}
// about.js
Copy the code
Configure mappings for nested subroutes
- Configure route mapping in route nesting
const routes = [
{
path: '/about'.component: About,
route: [{path: '/about'.component: AboutHistory,
exact: true
},
{
path: '/about/join'.component: AboutJoin,
},
]
}
]
// about.js (in the component rendered by Route: use props to fetch Route)
render() {
{ renderRoutes(this.props.route.route) }
}
Copy the code