当前位置:   article > 正文

react(40)——router路由之<Switch>组件_react router switch

react router switch

1.不加Switch的代码

import React, { Component } from "react";
import Div1 from "./components/div1"
import Div2 from "./components/div2"
import Page1 from "./pages/page1";
import Page2 from "./pages/page2";
import { Link, BrowserRouter, Route, NavLink } from "react-router-dom";

export default class App extends Component {
  render() {
    return (
      <div>
        <BrowserRouter>
          <NavLink activeClassName="acc" to="/a">
            a
          </NavLink>
          <NavLink activeClassName="acc" to="/b">
            b
          </NavLink>


          <Route path="/a" component={Page1} />
          <Route path="/b" component={Page2} />
          <Route path="/b" component={Page1} />
        </BrowserRouter>
        <Div1>123456789/Div1</Div1>
      </div>
    );
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  1. 如果没有Switch组件,当一个path匹配到多个component时,会渲染出多个组件。一个路径在匹配到了对应的component之后,还会接着向下匹配 ,会大大的影响效率。
    在这里插入图片描述

2.加了Switch组件之后

import React, { Component } from "react";
import Div1 from "./components/div1";
import Div2 from "./components/div2";
import Page1 from "./pages/page1";
import Page2 from "./pages/page2";
import { Link, BrowserRouter, Route, NavLink, Switch } from "react-router-dom";

export default class App extends Component {
  render() {
    return (
      <div>
        <BrowserRouter>
          <NavLink activeClassName="acc" to="/a">
            a
          </NavLink>
          <NavLink activeClassName="acc" to="/b">
            b
          </NavLink>

          <Switch>
            <Route path="/a" component={Page1} />
            <Route path="/b" component={Page2} />
            <Route path="/b" component={Page1} />
          </Switch>
        </BrowserRouter>
        <Div1>123456789/Div1</Div1>
      </div>
    );
  }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  1. 将Route组件包裹在Switch组件之中,当path匹配到一个component之后,将不会再想下继续匹配,提高了程序效率。
    在这里插入图片描述
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/65887
推荐阅读
相关标签
  

闽ICP备14008679号