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-routerCore library:
  • react-router-dom: a library used on the Web side based on the core library
  • react-router-nativeThe React Native library is based on the core library
  • react-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. Recommendedconnected-react-routerFor use with Redux

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 componentsThe router,The < BrowserRouter >, < HashRouter >
  • route matching componentsRoute matcher,< the Route >, < the Switch >
  • navigation componentsNavigation,<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
  • BrowserRouterContainer, used for storageRouter,Link
    • BrowserRouterThe following properties are provided
      • basename (string)The base URL for the current location
      • forceRefresh (boolean), whether the entire page is refreshed during navigation
      • getUserConfirmation (func), the function that is executed when the navigation needs validation. The default value is window.confirm
      • keyLength (number)The length of location.key. The default is 6
      • children (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

  • RouteRender the Component of the Route when location matches the path of the Route
    • Route accepts three rendering methods
      • <Route component>
      • <Route render>
        • renderFunction 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>
      • childrenFunction type, thanrenderMuch moreThe match parametersYou 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
    • exactWhether to perform exact matching, routing/aYou can and/ a /, / amatching
    • strictSpecifies whether to match strictly. Indicates that only the paths ending with slashes are matched/aYou can and/aMatch, cannot match/a/Match, compareexactIt’s more strict
    • path (string)Identifies the Route’s path. A Route without a path attribute will always match
    • componentRepresents the component that the path corresponds to
    • location (object)In addition to passing routing paths through path, a match can also be made by passing location objects
    • sensitive (boolean)Whether the matching path is case sensitive
    • Route components all receiveLocation, History, matchThree props
      • The three props are commonly used as match. You can use mate. params to obtain the value of the dynamic parameter
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
  • SwtichThe 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

  • LinkDeclares a route to jump to
    • To (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
  • NavLinkFunction andLinkSimilar but with more parameters, and you can set the style or class when selected
    • exact (boolean)Whether an exact match is performed
    • strict (boolean)Whether a strict match is performed
    • To (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 style
    • activeStyle (Object)The style applied to the element when it is selected
    • isActive(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
  • RedirectRedirection component
    • from (string)The path to be redirected can include dynamic parameters
    • push (boolean)When true, the redirect pushes the new entry into history rather than replacing the current entry
    • to (string | object)Path redirected to
    • exact (boolean)Whether to match from exactly
    • strict (boolean)Whether to strictly match from
    • sensitive (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