笔记react router 4(四)

  看完Router的变化,接着来讲<Switch>组件。react

在3.X中,你能够指定不少子路由,可是只有第一个匹配的路径才会被渲染。code

就像这样,component

<Route path='/' component={App}>
  <IndexRoute component={Home} />
  <Route path='about' component={About} />
  <Route path='contact' component={Contact} />
</Route>

4.X中提供了一个类似的方法用来代替<IndexRoute>,就是<Switch>组件,当一个<Switch>组件被渲染时,react只会渲染Switch下与当前路径匹配的第一个子<Route>blog

就像这样,路由

<Route path="/" render={()=>
       <Admin>
             <Switch>
                   <Route path='/home' component={Home} />
            <Route path='/about' component={About} />
            <Route path='/contact' component={Contact} />
</Switch> </Admin> } />

  正如你所理解的意思同样,switch就同咱们代码中使用的同样,当匹配到一个值以后,即再也不继续匹配,具备break的做用。所以,若是咱们须要严格匹配,就须要在Route上加上exatc属性。it

可是要注意,若是你的组件如例子中使用了嵌套,那么外层路由就不能够加exatc了。class

相关文章
相关标签/搜索