The installation

npm i react-router-dom --save
Copy the code

Container components

  • BrowserRouter browser comes with H5 API, restful style, need to cooperate with the background;
  • HashRouter Uses hash to route routes, and every path has # after it
  • MemoryRouter manages history in memory, and the address bar does not change. Used in reactNative.

Use of routes

  1. Run path by
//Home.js

import React,{Component}from 'react'
export default class Home extends Component{
    render() {return(
        <div>
        Home
        </div>
        )
    }
}

//User.js

import React,{Component}from 'react'
export default class Home extends Component{
    render() {return(
        <div>
      User
        </div>
        )
    }
}

//Profile.js

import React,{Component}from 'react'
export default class Home extends Component{
    render() {return(
        <div>
        Home
        </div>
        )
    }
}

//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { HashRouter, Router, Route } from 'react-router-dom'

import Home from './components/Home'
import User from './components/User'
import Profile from './components/Profile'


ReactDOM.render(<HashRouter>
  <div>
    <Route path="/home" component={Home} />
    <Route path="/profile" component={Profile} />
    <Route path="/user" component={User} />
  </div>
</HashRouter>, document.getElementById('root'));
Copy the code
  • A HashRouter can contain only one root element, so a div tag is wrapped around all routes as high as possible. For example, the index file in the main entry is a component and can be used directly with <> because only routes configured under the HashRouter are useful
  • The Route component has two properties
    • path
    • Component Displays the component of the Component property when the URL in the browser address bar matches the path

Route matching rule

  • Set path to/if a component wants all routes to be displayed

The Link component is built into the React-router-DOM and works like VueRouter and router-link to jump to the specified route

  • When used, it needs to be imported. You can set a to attribute value for it, which is the path to jump to the route when the single Link is used (Link will be rendered as a tag to display).
  • So keep as few A tags as possible in your development because routes have hash mode and history mode; Write Link It will automatically switch paths based on mode;
  • Path must be registered in Route (as long as it is registered in the application).

NavLink does the same thing as Link, except that when the current navigation is activated (NavLink’s to is activated at the same time as the path in the page URL) it adds an active class name to the currently active NavLink; Style the active class name if you set it to highlight the currently active navigation

Secondary routes are similar to VueRouter’s route nesting. You can directly define links where necessary to switch routes

Dynamic routing and route hopping

– Dynamic routes include an unfixed path, such as /user/detail/: ID, and the last /: ID. Dynamic routes are used to transfer data between pages. Dynamic routes also need to be registered in the Route

This is a static route

<Route path='/user/detail' component={Home}></Route>   
Copy the code

This is a dynamic route, it is not the same route as the one above, id is required

<Route path='/user/detail/:id' component={Home}></Route>
Copy the code

When we jump to dynamic routing, the following ID can be concatenated directly

<Link to={`/user/detail/${item.id}`} >Copy the code

If we need to get the dynamic part behind the dynamic route, we use the props. Match. params property, where the value is an object in which the dynamic parts are stored

ComponentWillMount,let { id } = this.props.match.params
Copy the code

Programmatic navigation uses code to switch routes

All descendant components rendered by routes such as HashRouter have a routing information object history in their props, where a method push is used to switch routes. The parameter takes a route path this.props.history.push(‘/home’) // constructor constructor is the first parameter props

Routing matching

Route matching is fuzzy by default. When multiple routes are matched, multiple components will be rendered. This is obviously not what we want

<Route exact path='/home/list' component={list}></Route>
Copy the code

This will render the compoent only if the route is /home/list and not if the route is /home

The render property value is a function that returns a JSX object or component

When the path of the URL in the page changes to match the path in Route, the render function executes and renders the JSX or component it returns to the page

The Switch component needs to be imported. When a Route matches a Route, the component is not used later

Put all the Route components into the Switch component, so that when one Route is matched, no other routes are matched

<Switch>
  <Route path='/'Exact render = {() = > < h1 > home page < / h1 >} > < / Route > < the Route path ='/home' component={Home}></Route>
  <Route path='/login' component={Login}></Route>
  <Route component={NotFound}></Route>
</Switch>

Copy the code

Set up the 404 Not Found page

Just write a Route with no path,

 <Route component={NotFound}></Route>
Copy the code

This will render the NotFound component when there is an unmatched route

Create-reat-app creates a project configuration agent

In the original create-React-app scaffolding, the agent was configured through the package.json configuration file. However, in the new version of scaffolding, only one proxy can be configured through package.json. You can’t do this if you need to configure multiple agents.

  • The new proxy configuration is configured using the/SRC/setupproxy.js file. Create a new file setupproxy.js under SRC
/ const proxy = require('http-proxy-middleware')

module.exports = function(app) {
    app.use(
        proxy(
            '/api', {
                target: 'http://localhost:8888',
                changeOrigin: true,
secure: false}))} this file will be referenced automaticallyCopy the code

Protected routing && Custom menu activation style

In a real project, we would protect some routes, such as pages that users are not allowed to access if they are not logged in. VueRouter has navigational guards to handle this problem, whereas in react-Router we need to write protected routes to implement protected routes. In essence, we implement a component to wrap the Route component and replace it with our own component. We make logical judgments in our own components

import React, { Component } from 'react'
import { Route, Redirect } from  'react-router-dom'

exportdefault ({component: Component, ... others}) => {return<Route {... Others} render={(props) => {// props is a router object that contains information about the current routereturn localStorage.getItem('loginSystem')
      ? <Component {...props} />
      : <Redirect to={{pathname: '/login', from: props.match.url}} />
  }
  }></Route>
}
Copy the code

This is a Protected component. Import PrivateRoute from ‘./components/Protected’

  • Pass a path and component to the protection component we write. The protection component is a function component. The to and component we pass are passed to the first argument object of the function component. We just deconstruct it and rename component (uppercase component to distinguish it from the native tag), put Component and other props like to in others, and then protect the component by returning a Route component. Render is a method that takes the router object and contains information about the current Route. The render function needs to return a JSX object or component, which will be executed when the url of the page matches the current Route, and the returned JSX object or component will be rendered.
  • Redirect is a component of the react-router-DOM. The to attribute is the route path to be redirected to. The value of the TO attribute is an object. The other properties are called a Location object and passed to the props of the redirected routing component
  • What if the user needs to jump back to the current page after login?
  • The route object of the render function above has our current route address, which we can get from props.match-url, and pass it to the user when we redirect to the login page, and then cut back to the user after the user has logged in programmatically: This.props.history.push(this.props.location.from) can also be used to implement other functions with protected components

Custom menu styles

We knew when we wrote vUE that we could add router-link-Action class styles to vue when navigation is activated. What about react-Router? Again, use component wrappers to implement custom MenuLink components

import React, { Component } from 'react'

import { Route, Link } from 'react-router-dom'

export default ({ to, label }) => {
  return <Route path={to} children={(props) => {
    return <li className={props.match ? 'active' : ' '}>
      <Link to={to}>{label}</Link>
    </li>
  }
  }></Route>
}
Copy the code
  • The MenuLink component returns a Route component. In the Route component, there is a children property. The property value is still a method, and the parameter of the method is also the routing information object.

  • If the route is active the match property in the current route object is an object, if it’s not active the match property is null, and that’s what we do, if it’s active we add the active class name, if it’s not active we don’t add it, and the active class name is what we define as the checked style

  • Difference between children and render: Although the value is a function that returns a JSX object or component render called when the page’s URL matches the current Route, the JSX object or component render children will be called regardless of whether the page’s URL matches the current Route. The returned JSX object or component will be rendered

  • The trick is the same: wrap the Route with our component, make a logical judgment in our price and selectively return a Route component

Antd (Ant Design) is introduced and used on demand

英 文 名 称 : ant. Design /docs/react/…

Antd is introduced on demand

  • The create-react-app setup project introduces ANTD and configures Less as required

  • In creat-react-app, the webpack files are hidden. The directive to expose wenpack files is YARN eject. Before using this command, push the git file once, or delete the git file

  • After the run, it will ask if it is exposed. Type y.

  • There will be an extra Config folder in the project directory.

  • Introduce ANTD on demand:

  • Install babel-plugin-import NPM I babel-plugin-import-sava

  • “Babel “: {“presets”: [“react-app”], “plugins”: [[“import”, {“libraryName”: “Antd “, “style”:” CSS “// import style CSS // style is true default import less}]]}

  • You can use import {Button} from ‘antd’ directly, without importing the global import ‘antd/dist/antd. CSS ‘and import Button from ‘antd/es/ Button’.

  • Less is not configured in the creat-react-app setup project by default. If you want to configure less, you need to use NPM run eject to expose the configuration file to install less: NPM I less less-loader-save

  • Finding the webpack.config.js file in the exposed Webpack requires first adding const lessRegex = /.less to the stack of cosnt constant definitions above/; This is used to identify less

Then add the following code to the rules of its Module: {test: lessRegex, exclude: lessModuleRegex, use: getStyleLoaders({importLoaders: 2, sourceMap: isEnvProduction && shouldUseSourceMap, }, ‘less-loader’ ), // Don’t consider CSS imports dead code even if the // containing package claims to have no side effects. // Remove this When webpack adds a warning or an error for this. // See github.com/webpack/web… sideEffects: true, }, { test: lessModuleRegex, use: getStyleLoaders( { importLoaders: 2, sourceMap: isEnvProduction && shouldUseSourceMap, modules: true, getLocalIdent: getCSSModuleLocalIdent, }, ‘less-loader’ ), },