React-Router


Front-end routing rules

The URL hash

  • URLthehashThe anchor point (#) is essentially a changewindow.locationthehrefattribute
  • We can just assignlocation.hashchangeurl, 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:

  • hashThe advantage is better compatibility. In the old version,IECan 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-routerIs the core part of the router code;
    • react-router-domIs for browsers;
    • react-router-nativeIs for native applications;
  • At present we use the latest onesReact RouterVersion isv5Version:
    • In factv4The version andv5Is not that different;
  • The installationreact-router:
    • The installationreact-router-domIt will help us install it automaticallyreact-routerRely on;
    • yarn add react-router-dom

Basic use of Router

The main API of the React-Router is the “components” provided to us.

  • BrowserRouterorHashRoutercomponent
    • RouterContains a listen for path changes and passes the corresponding path to the child component
    • BrowserRouterUsing thehistorymodel
    • HasRouterUsing thehashmodel
  • LinkThe component andNavLinkcomponent
    • In general, the path is used when jumpingLink, will eventually be rendered asaThe element
    • NavLinkIs in theLinkAdded some style properties on top of it (learn later)
    • toProperties:linkThe most important property in a component that sets the path to jump to
  • Routecomponent
    • Route Is used to match paths
    • pathProperty: The path to which the user sets the match
    • componentProperty: Sets the path to match after rendering the component
    • exactAttribute: 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 useNavLinkComponent to replaceLinkcomponent
    • activeStyle: Active (matching) style
    • activeClassName: 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 onepathOnce 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/aboutWhen the path matches,/:useridIt was also matched, and the last oneNoMatchComponents are always matched to

  • The reason? By default,react-routerAs long as the path is matchedRouteCorresponding componentWill 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 pointSwitchTo put allRoutePackage components

Redirect to Redirect

  • Redirect Redirect is used to Redirect routes. When this component is present, the Redirect is performedtoIn 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 obtainhistoryobject
    • Method 1: If the component isJump directly through the routeCan be directly frompropsPropertyhistory, location, match
    • Method 2: Obtain it from the App componenthistoryObject that needs to be usedwhitRouter** Advanced components **
      • AppComponents must be wrapped inBrowserRouterorHashRouterWithin a component
      • AppComponents usewithRouterAdvanced component packages
// 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-configTo complete the
  • The installationreact-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