Switch
为了解决
route
的唯一渲染,它是为了保证路由只渲染一个路径。
如果配置了<Switch>
<Router history={history}>
<Switch>
<Route path='/home' render={()=>(<div>首页</div>)}/>
<Route path='/home' component={()=>(<div>首页</div>)}/>
</Switch>
</Router>

如果没有配置<Switch>
<Router history={history}>
<Route path='/home' render={()=>(<div>首页</div>)}/>
<Route path='/home' render={()=>(<div>首页</div>)}/>
</Router>
<Switch>
是唯一的,因为它仅仅只会渲染一个路径,当它匹配完一个路径后,就会停止渲染了。相比之下(不使用<Switch>
包裹的情况下),每一个被location
匹配到的<Route>
将都会被渲染。

exact
只有页面的路由和
<Route>
的path
属性精确比对后完全相同该<Route>
才会被渲染。
这里想实现一个功能,项目刚进来的时候,路由默认为/
,这时候默认进页面路由一,如果页面改成其他的,跳转其他页面。
<Router history={history}>
<Switch>
<Route path='/' render={()=>(<div>页面一</div>)}/>
<Route path='/home' component={()=>(<div>页面二</div>)}/>
</Switch>
</Router>

会发现不管路由怎么切换,始终渲染的都是path
为/
的页面,这是因为/
匹配所有页面,所以不管路由怎么切换,始终渲染页面一。针对以上问题,我们可以采取调整顺序的解决办法,就是将path
为/
的路由放到最后,因为Switch
的特性,只要页面匹配完一个路径,它就停止渲染。
<Router history={history}>
<Switch>
<Route path='/home' component={()=>(<div>页面二</div>)}/>
<Route path='/' render={()=>(<div>页面一</div>)}/>
</Switch>
</Router>

当然,这样可以解决办法,但是如果每次书写路由的话都需要严格控制书写路由顺序的话那代码真的很不优雅,那有没有好的解决办法呢?那肯定必须是有的,官方给我们提供了exact
,就是精准匹配。
<Router history={history}>
<Switch>
<Route path='/' exact render={()=>(<div>页面一</div>)}/>
<Route path='/home' component={()=>(<div>页面二</div>)}/>
</Switch>
</Router>

网友评论