NPM package differences

React-router and react-router-dom are the NPM packages of the react-router and react-router-dom. The difference between them is that the latter has some DOM apis, such as Link, BrowserRouter, and HashRouter. React-router-dom has some of the apis required by the browser, while react-router only has the core API, so let’s summarize

  • React-router Specifies the core routing function package
  • React-router-dom Specifies the react route used by the browser
  • React-router-native Indicates the react route used by the app

React-router-dom and react-router-native inherit from react-Router, so we only need to introduce react-router-DOM in the browser development

The react – the router – dom API, rounding

The framework I first learned was VUE, which uses configuration files to configure routes, while React uses JSX to configure routes, so it was a bit awkward for me to learn at first.

HashRouter and BrowserRouter

These are the hash and history modes of the route, and the two components are containers for the route and must be in the outermost layer

/ / hash patternReactdom.render (<HashRouter> <Route path="/" component={Home}/> </HashRouter>) <BrowserRouter> <Route path="/" component={Home}/> </BrowserRouter> )Copy the code

Let’s talk about the parameters on HashRouter and BrowserRouter

  • Basename =”/web”; basename=”/web”; basename=”/web”
  • GetUserConfirmation is used to intercept the Prompt component and decide whether to jump
  • ForceRefresh sets whether to force a full browser refresh. The default value is false
  • KeLength is used to set the length of location.key, which defaults to 6 and is customizable

Prompt

Prompt is used to Prompt the user whether to jump or not. By default, window.confirm is used to Prompt the user. You can combine getUserConfirmation to create a custom Prompt

<Prompt message={location => {
    return 'Please confirm'}}/> If you return directlytrue, does not pop upCopy the code

Route

Route is a raw material of the Route. It is the component that controls the display of the corresponding path

The parameters of the Route

  • Path Indicates the jump path
  • Component Indicates the component displayed in the path
  • Render can write its own render function to return the concrete DOM without setting the Component
  • Location passes a route object, compares it to the current route object, and jumps if it matches
  • Exact matches rules. True matches rules exactly.
path url Whether open Matching results
/a /a/b false yes
/a /a/b true no
  • Sensitive Indicates whether the path is case-sensitive
path url Whether open Matching results
/a /a true yes
/a /A true yes
  • Strict indicates whether the following/matches
path url Whether open Matching results
/a /a/ true yes
/a /a/c true yes
/a /a true no

Router

Low-level routing, applicable to any routing component, is mainly deeply integrated with Redux, and must be used with the history object. The purpose of using Router routing isto synchronize with the history in a state management library such as Redux

<Router history={history}>
    ...
</Router>
Copy the code

The Link and NavLink

Both are jump routes, and NavLink has more parameters

The Link of the API

  • There are two ways of writing to, which indicates the route to be forwarded
    • String writing
      <Link to="/a"/>
      Copy the code
    • Object to write
      <Link to={{
        pathname: '/courses'.search: '? sort=name'.hash: '#the-hash'.state: { fromDashboard: true}}} / >Copy the code
  • Replace just changes push to replace
  • The innerRef accesses the DOM of the Link tag

NavLink API

  • Link all apis
  • ActiveClassName Class name set when the route is activated
  • ActiveStyle Style of route activation Settings
  • Exact refers to the Route. The active class is activated only when this condition is met
  • Strict refers to Route. The active class is activated only if this condition is met
  • IsActive receives a callback function that is triggered when the active state changes, or breaks the jump if it returns false
const oddEvent = (match, location) => { console.log(match,location) if (! Match) {return false} console.log(mate.id) return true} <NavLink isActive={oddEvent} to="/a/123">Copy the code
  • Location receives a Location object and jumps only when the URL meets that object’s criteria
<NavLink to="/a/123" location={{ key:"mb5wu3".pathname:"/a/123"}} / >Copy the code

Redirect

Redirect Redirection is simple, we just look at the code

// Basic redirection
<Redirect to="/somewhere/else" />

// Object form
<Redirect
  to={{
    pathname: "/login".search: "? utm=your+face".state: { referrer: currentLocation }
  }}
/>

// Use push to generate new records
<Redirect push to="/somewhere/else" />

// Used with the Switch component, the form represents the path before the redirection. If the path matches, it is redirected. If the path does not match, it is not redirected
<Switch>
  <Redirect from='/old-path' to='/new-path'/>
  <Route path='/new-path' component={Place}/>
</Switch>
Copy the code

Switch

Route switching matches only the first Route. Imagine that the Switch TAB contains only the Route, Redirect, and Router

<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/about" component={About}/>
  <Route path="/:user" component={User}/>
  <Route component={NoMatch}/>
</Switch>
Copy the code

withRouter

When a non-routed component also wants to access the match, Location, and History objects of the current route, withRouter is a good choice, and can be interpreted as wrapping a component into a routed component

import { withRouter } from 'react-router-dom'
const MyComponent = (props) = > {
    const { match, location, history } = this.props
     return (
        <div>{props.location.pathname}</div>)}const FirstTest = withRouter(MyComponent);
Copy the code

The history object

Vue-router has component-like navigation and programmatic navigation. How does the React-Router use its API to control forward, backward, and refresh? This is where the history object comes in

In each routing component, we can use this.props. History to get the history object, or we can use withRouter to wrap the history object. In the history component, we encapsulates methods like push, replace, and go

History {
    length: number; action: Action; location: Location; push(path: Path, state? : LocationState):void; // Call push to advance to an address that can accept a state object, which is custom routing data
    push(location: LocationDescriptorObject): void; // Accept a description object for locationreplace(path: Path, state? : LocationState):void; // Replace the current path with a page, no goBack
    replace(location: LocationDescriptorObject): void; / / same as above
    go(n: number): void; // Go forward how much also page
    goBack(): void; // Return a page
    goForward(): void; // Proceed to a pageblock(prompt? : boolean | string | TransitionPromptHook): UnregisterCallback; listen(listener: LocationListener): UnregisterCallback; createHref(location: LocationDescriptorObject): Href; }Copy the code

So we can call the history method if we want to use the API to move forward and backward

Reference documentation

  • Reacttraining.com/react-route…
  • www.jianshu.com/p/c6fad9831…