Advanced usage of route@5

  1. Routing components and general components

    1. General components are placed in the src-components tag, but routing components are not in compliance with the specification. When standardizing development, routing components should be placed in src-pages.


    2. The general component writing method is <Header/>, and the routing component writing method is <Route path='/demo' component={Demo}/>.


    3. The general component props is {} if it is not passed; the routing component also has props {history:{}, location:{}, match:{}} fixed three properties.

      The encoding needs to be used in the three attributes are:

      history:

      • go: f go(n)
      • goBack: f goBack()
      • goForward: f goForward()
      • push: f push(path, state)
      • replace: f replace(path, state)

      location:

      • pathname: “/about”
      • search: “ “
      • state: undefined

      match:

      • params: {}

      • path: “/about”

      • url: “/about”


  2. NavLink

    If the route link is highlighted, or a dynamic class name needs to be appended when clicking, you cannot use <Link> , use <NavLink> . The mechanism of NavLink is to append a class name to the element currently being clicked, and the class name is active. (The mechanism of Bootstrap is that whoever is active will be highlighted. This matches NavLink exactly.)


    But sometimes you don’t use Bootstrap, or you don’t want to use the active category. This requires the use of an attribute of NavLink: activeClassName=” “, which can specify the highlighted class name. When using this property, add !important to the style to increase the weight (to exceed the Bootstrap default weight) (there is a bug here).


  3. wrapped NavLink component

    If it is not encapsulated, the code repetition is too high (the repeated content is activeClassName and className). Encapsulated as <MyNavLink> (generic component).

    1
    2
    3
    4
    5
    6
    7
    import { NavLink } from 'react-router-dom'

    export default class MyNavLink extends Component {
    render() {
    return (
    <NavLink activeClassName="test" className="item" {...this.props}/>
    )}}
    1
    <MyNavLink to="/home">Home</MyNavLink><br/> //Use the same as NavLink, repeat the code to write to MyNavLink

    Note here the delivery method of tag body content (Home in the example). The content of the component tag body is a special tag property: props.children. In a tag, instead of writing the content in the content of the tag body, write the content directly with children=” “ in the tag, and the content can also be displayed.

    1
    <p children="label body content"/> //This will display the label content normally.

    In the example code block, use {...this.props} to write props.children into the tag together, that is, to display the content normally.

  4. Use of Switch

    If a path corresponds to two components, both components will be rendered, but this is not normal code. The routing mechanism is that after the path matches the component, it will continue to match, which leads to low efficiency. The @5 version uses <Switch></Switch> to wrap the routing component to solve this problem. Once the path is matched to the component, it will not continue to match. (Use Switch when more than one route is registered)

    1
    2
    3
    4
    <Switch>
    <Route path="/about" component={About}>
    <Route path="/home" component={Home}>
    </Switch>

  1. Solve the problem of missing styles

    Trigger condition for style loss: The navigation link uses multiple / (non-nested routes) such as /a/b and uses bootstrap. After the page is rendered, the style may be lost. (The new version should have been fixed) You can hold down SHIFT and refresh every time you refresh, and force the refresh without leaving the cache.


    Reason analysis: In the network, look for the bootstrap.css file, the status is 200 (success), and the style is not lost here. Click here to find the bootstrap.css address http://localhost:3000/css/bootstrap.css . This is the address of bootstrap.css in the scaffolding. (where http://localhost:3000 is the scaffolding built-in server (created by devServer in webpack), and public is the root path of http://localhost:3000.) The validity of the bootstrap.css address can be verified directly in the browser Look at this address, or the response next to the header in the network.


    But when the /a/b structure is used, the bootstrap.css file, the status is 304. After clicking it, I found that the address is http://localhost:3000/a/css/bootstrap.css , that is, /a in the /a/b structure is considered to be part of the root path, so the address of the css file is wrong. At this time, the response returned is index.html. This is because there is a mechanism in the scaffolding, that is, if a non-existing resource is requested with an address, the scaffolding will render the index.html in public. The error reported here is Resource interpreted as Stylesheet but transferred with MIME type text/html: “http://localhost:3000..."


    There are three solutions:

    1. In the public index.html, change the css import path from href='./css/bootstrap.css' to href='/css/bootstrap.css' (remove .). The principle here is to change the relative path of ./ to the absolute path of /. / means to go directly to http://localhost:3000 to request content. This is generally used.

    2. In index.html, the css import path is changed to href='%PUBLIC_URL%/css/bootstrap.css' . %PUBLIC_URL% represents the absolute path to the public file. This scenario is limited to React scaffolding.

    3. In index.js under src, BrowerRouter is changed to HashRouter. After the change, the root path becomes http://localhost:3000/#/ . # are considered front-end resources and are not brought to the server, such as http://localhost:3000/#/a/b .


  2. routing fuzzy matching and strict matching

    Fuzzy matching: to="/home/a/b" in the <Link> class tag provides many paths, but <Route> requires fewer paths for path="/home", you can match to. When matching, it matches in the order of /home /a /b, and /home matches path="/home" in the <Route> tag, and the match is successful. However, if the order is wrong, such as /a /home /b, the match cannot be successful, because if /a does not match, it will be considered a match failure.


    Exact match: The paths must match exactly. <Route exact={true} path="/about" component={about}/>. That is, exact={true} is added to the <Route> tag. Shorthand can directly write exact, omitting ={true}.


    In actual work, try not to use strict matching, which will cause serious problems. The principle of use is that if you can not enable strict matching, you will not enable it. If there is a problem with fuzzy matching, then enable strict matching.


  3. Redirect implements preselection

    In the previous way of writing, no routing components are displayed after opening the page, and the page needs to be clicked on the navigation link. But we want to have a default routing component. Implementing default routing requires Redirect redirection. (Deprecated in @6, changed to Navigate)


    Note that http://localhost:3000 (same as http://localhost:3000/ ) is for route matching. / is an empty string, matching no components. <Redirect to="/about"/> should be placed at the bottom of the routing component, as a catch-all item (similar to the else in if) to redirect addresses that do not match the routing component to a routing component.


    1
    2
    3
    4
    5
    6
    import {Redirect} from 'react-router-dom';
    <Switch>
    <Route path="/about" component={about}/>
    <Route path="/about" component={about}/>
    <Redirect to="/about"/>
    </Switch>

Share