Switch的作用:Switch可以提高路由匹配效率(单一匹配)。
例:
import React, { Component } from 'react'
import {Route,Switch} from 'react-router-dom'
import Home from './pages/Home' //Home是路由组件
import About from './pages/About' //About是路由组件
import Header from './components/Header' //Header是一般组件
import MyNavLink from './components/MyNavLink'
import Test from './pages/Test1'
export default class App extends Component {
render() {
return (
<div>
<div className="row">
<div className="col-xs-offset-2 col-xs-8">
<Header/>
</div>
</div>
<div className="row">
<div className="col-xs-2 col-xs-offset-2">
<div className="list-group">
{/* 原生html中,靠<a>跳转不同的页面 */}
{/* <a className="list-group-item" href="./about.html">About</a>
<a className="list-group-item active" href="./home.html">Home</a> */}
{/* 在React中靠路由链接实现切换组件--编写路由链接 */}
{/* <NavLink activeClassName="atguigu" className="list-group-item" to="/about">About</NavLink>
<NavLink activeClassName="atguigu" className="list-group-item" to="/home">Home</NavLink> */}
<MyNavLink to="/about">About</MyNavLink>
<MyNavLink to="/Home">Home</MyNavLink>
</div>
</div>
<div className="col-xs-6">
<div className="panel">
<div className="panel-body">
{/* 注册路由 */}
<Switch>
<Route path="/about" component={About}/>
<Route path="/home" component={Home}/>
<Route path="abc" component={ABC} />
<Route path="abc" component={ABC} />
<Route path="abc" component={ABC} />
<Route path="abc" component={ABC} />
<Route path="abc" component={ABC} />
<Route path="abc" component={ABC} />
<Route path="abc" component={ABC} />
<Route path="abc" component={ABC} />
<Route path="abc" component={ABC} />
<Route path="/Home" component={Test}/>
</Switch>
</div>
</div>
</div>
</div>
</div>
)
}
}
代码描述:
上述代码使用封装好的MyNavLink分别指向了
/about
/home
然后使用Route来设置对应的地址展示的路由组件
Switch作用体现:
由于路由的默认是多次匹配(既:通过for循环遍历一遍每个路由组件,找到所有对应该路径的路由组件来展,如果路由组件很多的话造成了效率过低)
这里用Switch包裹Route来实现单一匹配,既一个路由对应第一个该路由的路由组件。原理为遍历到该路由组件后,停止遍历。