React Router Is a Router that you can’t React with
This article is based on React-router-DOM 5.2.0
The basic concept
react-router
Core library:react-router-dom
: a library used on the Web side based on the core libraryreact-router-native
The React Native library is based on the core libraryreact-router-config
: library for configuring static routes- With the introduction of React Router V4, there is no more centralized routing configuration
react-router-redux
: a library that integrates Redux- No longer recommended. Recommended
connected-react-router
For use with Redux
- No longer recommended. Recommended
There is no need to install the core library. If you only use it in the browser, install react-router-dom directly
Demo
/// app.jsx import React from 'react'; import {BrowserRouter as Router, Route, Link} from 'react-router-dom'; import Byd from './byd'; import Car from './car'; const App = () => { return ( <> <div>App page</div> <Router> <Link to='/'>Car</Link> <Link to='/byd'>Byd</Link> <br/> <Route path='/' exact component={Car}></Route> <Route path='/byd' component={Byd}></Route> </Router> </> ); } export default App; . /// byd.jsx import React from 'react'; const Byd = () => { return ( <div>Byd</div> ); } export default Byd; . /// car.jsx import React from 'react'; const Car = () => { return ( <div>Car page</div> ); } export default Car;Copy the code
The basic components
The React Router has three components:
router components
The router,The < BrowserRouter >, < HashRouter >
route matching components
Route matcher,< the Route >, < the Switch >
navigation components
Navigation,<Link>、<NavLink>、<Redirect>
Other routing components include the
memory routing component, the
Native routing component, and the
static routing component. MemoryRouter is mainly used in non-browser environments such as ReactNative, so the HISTORY of the URL is stored directly in the content. StaticRouter is primarily used for server-side rendering
The router
React-router-dom provides BrowserRouter and HashRouter routes, both of which create a dedicated history object. The main difference between the two is how they store urls and communicate with the Web server
BrowserRouter
http://localhost:3000/byd
The URL generated by HashRouter http://localhost:3000/#/byd is different from that generated by HashRouter http://localhost:3000/#/byd
import { BrowserRouter, Route, Link } from "react-router-dom";
Copy the code
BrowserRouter
Container, used for storageRouter
,Link
BrowserRouter
The following properties are providedbasename (string)
The base URL for the current locationforceRefresh (boolean)
, whether the entire page is refreshed during navigationgetUserConfirmation (func)
, the function that is executed when the navigation needs validation. The default value is window.confirmkeyLength (number)
The length of location.key. The default is 6children (node)
The child node to render
The HashRouter does not support location.key and location.state, so BrowserRouter is recommended in the browser
Route matching machine
Route
Render the Component of the Route when location matches the path of the Route- Route accepts three rendering methods
<Route component>
<Route render>
render
Function type, Route will render the return value of this function, you can add some extra logic to the function, so you can add some logic to render and return a component to render
<Route children>
children
Function type, thanrender
Much moreThe match parameters
You can use the match parameter to determine what to render when you match, and what to render when you don’t match
- Routes often use exact, path, and component attributes
exact
Whether to perform exact matching, routing/a
You can and/ a /, / a
matchingstrict
Specifies whether to match strictly. Indicates that only the paths ending with slashes are matched/a
You can and/a
Match, cannot match/a/
Match, compareexact
It’s more strictpath (string)
Identifies the Route’s path. A Route without a path attribute will always matchcomponent
Represents the component that the path corresponds tolocation (object)
In addition to passing routing paths through path, a match can also be made by passing location objectssensitive (boolean)
Whether the matching path is case sensitive
- Route components all receive
Location, History, match
Three props- The three props are commonly used as match. You can use mate. params to obtain the value of the dynamic parameter
- Route accepts three rendering methods
Belongs to | attribute | type | meaning |
---|---|---|---|
history | length | number | Represents the number of history stacks |
action | string | Represents the current action. Like POP, replace, or Push | |
location | object | Represents the current position | |
push(path, [state]) | function | Add a new entry to the top of the history stack | |
replace(path, [state]) | function | Replaces the current entry in the history stack | |
go(n) | function | Move the pointer forward in the history stack | |
goBack() | function | Equivalent to go (1) | |
goForward() | function | Equivalent to go (1) | |
block(promt) | function | Stop jumping | |
match | params | object | Represents the path parameter, the key-value pair obtained by parsing the dynamic portion of the URL |
isExact | boolean | If the value is true, it indicates an exact match | |
path | string | The path format used to make the match | |
url | string | The part of the URL that matches | |
location | pathname | string | The URL path |
search | string | Query string in URl | |
hash | string | Hash segmentation of the URL | |
state | string | Represents the state in location |
Swtich
The default behavior of a route is to render it as soon as it matches. This logic is fine in most scenarios, but consider the following scenario
Component ={dog}></Route> <Route path="/:dog" component={Husky}></Route> // The Route will still be matched so that both components will be rendered... <Switch> <Route path='/dog' component={dog}></Route> // Switch matches a Route and does not look for the next Route. <Route path="/:dog" component={Husky}></Route> </Switch>Copy the code
navigation
Link
Declares a route to jump toTo (string | object | function)
Path to jump to (pathName) or address (location)- String is an explicit path address
- Object has the following properties (that is, a Location object)
- Pathname: indicates the URL path.
- Search: query string in URl.
- Hash: Hash segment of the URL, such as #a-hash.
- State: indicates the status of location
- Function is a function that takes the current location as an argument and returns the location as a string or object
replace (boolean)
A value of true is used to replace a history, and a value of false is used to add a history
<Link to="/course" /> ... <Link to={{ pathname: '/course', search: '? sort=name', hash: '#the-hash', state: { fromDashboard: true } }} /> ... <Link to={location => ({ ... location, pathname: "/courses" })} /> <Link to={location => `${location.pathname}? sort=name`} />Copy the code
NavLink
Function andLink
Similar but with more parameters, and you can set the style or class when selectedexact (boolean)
Whether an exact match is performedstrict (boolean)
Whether a strict match is performedTo (string | object)
Path to jump to (pathName) or address (location)activeClassName (string)
Is the name of the class with the selected state to which we can styleactiveStyle (Object)
The style applied to the element when it is selectedisActive(function)
Add additional logic to determine if the link is active
<NavLink activeClassName='select' to='/'>Car</NavLink> // So that when the link is clicked, select is used instead of activeCopy the code
Redirect
Redirection componentfrom (string)
The path to be redirected can include dynamic parameterspush (boolean)
When true, the redirect pushes the new entry into history rather than replacing the current entryto (string | object)
Path redirected toexact (boolean)
Whether to match from exactlystrict (boolean)
Whether to strictly match fromsensitive (boolean)
Whether matching from is case sensitive
<Route path="/husky" component={husky}></Route> <Redirect to='/husky'/> // Redirect unmatched paths directly to /huskyCopy the code
Hooks components
- useHistory
- To get the history object for programmatic navigation
const Husky = props => { console.log(useHistory()); // The same result as props. History console.log(props. History); Return <div> Husky </div>; }; . <Route path="/dog" component={dog}></Route> <Route path="/husky"> < husky /> </Route> //Copy the code
- useLocation
- To get the Location object, you can view the current routing information
const Husky = props => { console.log(useLocation()); Console. log(props. Location); // The same result as props. Return <div> Husky </div>; };Copy the code
- useParams
- Can be used to get mate.params
Const Husky = props => {console.log(useParams()) // Same as props.mate.params, Console. log(props. Match-params) const {eat} = props. Match-params; Return (<div> husky eat {eat}</div>); }Copy the code
- useRouteMatch
- You can take a path string as an argument. UseRouteMatch returns the match object if the path argument matches the current path, or null otherwise.
// Accept a string as an argument const Husky = props => {const match = useParams('/ Husky '); Const {eat} = match? Const {eat} = match? match.params : ''; Return (<div> husky eat {eat}</div>); }Copy the code
Programmatic navigation
Route jumps can be made directly with push and replace in the history object