In the official tutorial of React-router-DOM, there are 12 examples in total. However, in my personal view, it is very tiring to have 12 examples, many of which are not standard enterprise project application. Therefore, I want to rewrite every example in the tutorial according to the requirements of enterprise project development. This tutorial is the first example — basic usage and introduction.

HashRouter or BrowserRouter

The React-Router works by placing a Router component at the top of the tree, which is littered with ReactR components. The Router component at the top analyzes and listens for URL changes, and the Route component under its umbrella reads the information directly.

The Router is the “provider” and the Route is the “consumer”.

Router is also a layer of abstraction, so that the following Route does not need the details of different URL design, do not think of URL design method, at least can be divided into two.

For example, / corresponds to the Home page and /about corresponds to the about page, but this design requires server-side rendering because the user can directly access any URL. The server must be able to return HTML for/as well as for /about.

There is only one path /, and the route is determined by the # section after the URL, /#/ corresponds to the Home page. /#/about corresponds to the about page. The URL after # is not sent to the server, so no matter which URL is the/path to the server, the server only needs to return the same HTNL, and then the browser side parses the part after # to complete the browser side rendering.

component

An advanced routing component that uses the HTML5 History API to keep your UI and URL in sync. This component has the following properties:

  1. Basename: string Adds a base URL for all locations. Usage scenario: If you need to deploy a page to a secondary directory on the server, you can use basename to set the page to this directory.
<BrowserRouter basename="/wsm" />
<Link to="/react"/> // Render to <a href="/minooo/react">
Copy the code
  1. GetUserConfirmation: func Navigates to the function to be executed at the front of the page. Window. confirm is used by default.
const getConfirmation = (message, callback) => {
  const allowTransition = window.confirm(message)
  callback(allowTransition)
}
<BrowserRouter getUserConfirmation={getConfirmation('Are you sure? ', yourCallBack)} />
Copy the code
  1. ForceRefresh: bool Mandatory page refresh when browser does not support HTML5 history API. Usage scenario: Same as above.
const supportsHistory = 'pushState' inwindow.history <BrowserRouter forceRefresh={! supportsHistory} />Copy the code
  1. KeyLength: number Sets the length of the location.key in the route. The default is 6. (The function of key: when clicking on the same link, the location.key under the route will change each time. You can refresh the page by changing the key.) Application scenario: Set this parameter as required.
<BrowserRouter keyLength={12} />
Copy the code

Finally, an example is shown:

<BrowserRouter
  basename="/minooo"
  forceRefresh={false}
  getUserConfirmation={getConfirmation()}
  keyLength={12}
></BrowserRouter>
Copy the code

Ship with three Render Methods and three props. Render methods are:

  1. Route component
  2. Route render
  3. Route children

Props are:

  • match
  • location
  • History All render methods without exception will be passed to these props.

component

A React Component is rendered only if the access address and route match, and this component accepts route props (match, location, history).

When using Component, the Router will use React. CreateElement to create a new React element based on the given Component. This means that if you use inline functions to pass values to Component, it will cause unnecessary reloading. For inline rendering, render Prop is recommended.

<Route path="/user/:username" component={User} />
const User = ({ match }) => {
  return<h1>Hello {match.params.username}! </h1> }Copy the code

To: string Function: To jump to the specified path Application scenario: For simple jump, the path in the form of a string is used.

Action scenario: For example, the page you click on the link to jump to needs to display the corresponding content of the link, or for example, this is a payment jump, needs to pass the price of goods and other information.

<Link to={{
  pathname: '/course',
  search: '? sort=name',
  state: { price: 18 }
}} />
Copy the code

This is a special edition, and as the name implies this is for page navigation. Navigation requires an “active state”.

ActiveClassName: String Navigation Select the style name to apply when activating. The default style name is Active

<NavLink
  to="/about"
  activeClassName="selected"
>MyBlog</NavLink>
Copy the code

Only the first or that matches the current access address is rendered.

Prompt

Make a prompt when the user leaves the page.

  • Message: string Prompt message set when the user leaves the current page.
  • Message: func Callback function set when the user leaves the current page
<Prompt message={location => (
  `Are you sue you want to go to ${location.pathname}? `)} / >Copy the code
  • When: bool Determines whether Prompt is enabled by setting conditions
<Prompt 
  when={this.state.dirty} 
  message="Data not saved, sure to leave?" />
Copy the code

Objects and methods

match

The match object contains information about how to match urls and has the following properties:

  • Params: object path parameter that retrieves key-value pairs by parsing the dynamic part of the URL
  • IsExact: bool Indicates true. All urls must be matched
  • Path: string Matching path pattern, used to create nested
  • Url: String The matching portion of the URL that is nested to obtain a match object in the following situations
  • In Route Component, this.props. Match
  • Get ({match}) => () in Route render
  • ({match}) => () in Route children
  • In withRouter, get this. Props. Match
  • The return value of matchPath

location

Location means where you are, where you are going, or where you were before

The Location object can be obtained in the following situations

  • In Route Component, this.props. Location
  • Get ({location}) => () in Route render
  • ({location}) => () in Route children
  • In withRouter, getting the location object as this.props. Location does not change, so you can use the location object in a lifecycle callback to see if the access address for the current page has changed. This technique is useful for retrieving remote data and using animations
componentWillReceiveProps(nextProps) {
  if(nextProps.location ! == this.props. Location) { }}Copy the code

Location can be used in different contexts:

  1. Link to={location} />
  2. NaviveLink to={location} />
  3. Redirect to={location />
  4. history.push(location)
  5. history.replace(location)

history

The history object is mutable because it is recommended to get the location from prop instead of directly from history.location. This ensures that the React hook function executes properly during the React lifecycle, such as the following code:

class Comp extends React.Component { componentWillReceiveProps(nextProps) { // locationChanged const locationChanged = nextProps.location ! == this.props. Location //falseBecause thehistoryIs the const variable locationChanged = nextProps. History. The location! == this.props.history.location } }Copy the code

Finally, a simple and complete React-router is implemented

import React, { Component } from 'react';
import './App.css';
import {
  BrowserRouter as Router,
  Link,
  Route,
  Switch,
} from 'react-router-dom';
import Home from './components/Home/Home'
class App extends Component {
  render() {
    const About = ( ) => <h1>About</h1>;
    const Nested = () => (
      <div>
        <Link to="/nested/one">One</Link>
        <Link to="/nested/two">Two</Link>
        <Link replace to="/nested/Three">Three</Link> <div> Select one click </div> <Route path="/nested/:minooo?" render={({match}) => <h2>URL: {match.params.minooo || 'minooo'}</h2>} />
      </div>
    )
    return (
      <div className="App">
        <Router>
          <Link to="/">Home</Link>
          <Link to={{ pathname: '/about',search:'? sort=name', state:{ price: 18 } }}>About</Link>
          <Link to="/contact/12? name=minooo">Contact</Link>
          <Link to="/blog">blog</Link>
          <Link to="/nested">Nested</Link>
          {/* <NavLink to="/about" activeClassName="active">MyBlog</NavLink> */}
        <main>
          <Switch>
            <Route exact path="/" component={Home} />
              <Route path="/about" component={About} />
            <Route path="/contact/:id" render={({ history, location, match }) =>
              <h1>
                {console.log(history, location, match)}
                <span onClick={() => {history.push('/', {name:'mm'})}}>click me</span>
              </h1>} />
              <Route path="/blog" children={({ match }) => (
                <li className={match?'active': ' '}>
                  <Link to="/">User</Link>
                </li>
            )} />
              <Route path="/nested"render={Nested} /> <Route render={() => <h1>Page not found</h1>} /> </Switch> </main> </Router> </div> ); }}export default App;

Copy the code