1. Use basic routes

  1. Clear the navigation area and display area on the interface

  2. The A label in the navigation area is changed to the Link label

    <Link to="/xxxxx">Demo</Link>

    <Link to="/home">Home</Link>
    <Link to="/about">About</Link>
    Copy the code
  3. The function pane writes Route labels to match paths

    <Route path='/xxxx' component={Demo}/>

    <Route path="/home" component={Home} />
    <Route path="/about" component={About} />
    Copy the code
  4. The outermost part of

    wraps a

    or


    ReactDOM.render(
        <BrowserRouter>
            <App />
        </BrowserRouter>.document.getElementById('root'));Copy the code

2. Routing components are different from common components

  1. Write different

    • General components:<Demo/>
    • Routing components:<Route path="/demo" component={Demo}/>
  2. Different storage locations

    • General components:components/
    • Routing components:pages/
  3. The props received are different

    • General components: What do I receive when I write component labels to pass

    • Routing component: Receives three fixed properties

      History: go: ƒ go (n)goBack: ƒ goBack ()goForward: ƒ goForward ()push: ƒ push (path, state)replace: ƒ replace (path, state)location:
      	pathname: "/about"
      	search: ""
      	state: undefined
      match:
      	params: {}
      	path: "/about"
      	url: "/about"
      Copy the code

3. NavLinkThe use of

NavLink enables routing links to be highlighted by specifying the style name via activeClassName.

<NavLink activeClassName="demo" to="/home">Home</NavLink>
<NavLink activeClassName="demo" to="/about">About</NavLink>
Copy the code

4. Secondary encapsulationNavLink

export default class MyNavLink extends Component {
    render() {
        return <NavLink activeClassName="active" {. this.props} / >; }}Copy the code
<MyNavLink to="/about">About</MyNavLink>
<MyNavLink to="/home">Home</MyNavLink>
Copy the code

5. SwitchThe use of

  1. In general,pathandcomponentIt’s a one-to-one correspondence
  2. SwitchThe efficiency of route matching (single match) is improved. After a match is successful, the route is not traversed
  3. use<Switch></Switch>The label will<Route />wrapped
<MyNavLink to="/about">About</MyNavLink>
<MyNavLink to="/home">Home</MyNavLink>

<Switch>
    <Route path="/about" component={About} />
    <Route path="/home" component={Home} />
</Switch>
Copy the code

6. Solve style loss problems

  1. public/index.htmlDo not write when introducing styles in. /Write,/(common)
  2. public/index.htmlDo not write when introducing styles in. /Write,%PUBLIC_URL%(common)
  3. useHashRouter

Strict matching and fuzzy matching

  1. The default isFuzzy matching(Input pathMust includeMatched pathAnd,Be consistent in order)
  2. Enable strict matching:<Route exact={true} path="/about" component={About}/>
  3. Strict match don’t just turn it on, you need to turn it on again. Sometimes, if this function is enabled, secondary routes cannot be matched

8. RedirectThe use of

It is written at the bottom of all route registrations. When all routes fail to match, the route specified by the Redirect is redirected.

<Switch>
    <Route path="/about" component={About} />
    <Route path="/home" component={Home} />
    <Redirect to="/home" />
</Switch>
Copy the code

9. Set routine by

  1. In the folder of the component for which you want to enable routing, create the component

  2. Enable child routes in the component. When registering child routes, write the path value of the parent route

  3. Routes are matched in the order in which they are registered

export default class Home extends Component {
    render() {
        return (
            <div>
                <h2>Home</h2>
                <div>
                    <MyNavLink to="/home/news">News</MyNavLink>
                    <MyNavLink to="/home/message">Message</MyNavLink>
                </div>
                <div>
                    <Switch>
                        <Route path="/home/news" component={News} />
                        <Route path="/home/message" component={Message} />
                        <Redirect to="/home/news" />
                    </Switch>
                </div>
            </div>); }}Copy the code

10. Pass parameters

For details, click React-Router to pass parameters.

11. pushandreplaceThe difference between

  • pushmodel

Routing can be understood as the data structure of the stack. In push mode, every address pushed onto the stack will form a history, which can be returned to the upper layer.

  • replacemodel

In replace mode, replacing the address at the top of the stack with the current address does not form a history and cannot be returned to the previous layer because the previous layer has been replaced.

React-router uses push mode by default. Replace mode can be enabled at route links:

<Link replace={true} to="/home/message/detail/id/title">title</Link>
Copy the code

12. Programmatic routing navigation

Use the API on the this.prosp.history object to jump, forward, and backward the operation route.

pushShow = (id, title) = > {
    // push+params
    this.props.history.push(`/home/message/detail/${id}/${title}`);

    // push+search
    this.props.history.push(`/home/message/detail/? id=${id}&title=${title}`);

    // push+state
    this.props.history.push(`/home/message/detail/`, { id, title });
};
replaceShow = (id, title) = > {
    // replace+params
    this.props.history.replace(`/home/message/detail/${id}/${title}`);

    // replace+search
    this.props.history.replace(`/home/message/detail/? id=${id}&title=${title}`);

    // replace+state
    this.props.history.replace(`/home/message/detail/`, { id, title }); }; . <button onClick={() = > {this.pushshow (msgobj.id, msgobj.title)}}> pushShow(msgobj.id, msgobj.title)<button onClick={()= >{this.replaceShow(msgObj.id, msgObj.title); }} > replace mode</button>
Copy the code

13. withRouterThe use of

  • withRouterCan be processedGeneral componentAnd letGeneral componenthaveRouting componenttheAPI
  • withRouterThe return value is a new component
import { withRouter } from 'react-router-dom'; .class Header extends Component {... }export default withRouter(Header);
Copy the code

14. BrowserRouterwithHashRouterThe difference between

BrowserRouter HashRouter
The underlying principle useH5thehistory APIAnd are not compatibleIE9And the following version useURLHash value, better compatibility
pathIn the form of None in the path#.localhost:3000/demo/test Path contains#.localhost:3000/#/demo/test
Refresh the routestateInfluence of parameters It doesn’t make any difference becausestateStored in thehistoryIn the object The refresh results in routesstateParameter loss!

Note: A HashRouter can be used to resolve some path error-related problems.