react-router3.0 升级为react-router4.0后不再支持 多个<Route>并列在一个<Router>组件中,而要包含<Switch>
react-router3.0中嵌套路由写法:
<Router history={history}>
<Route path='/' component={IndexPage}>
<Route path='/bar' component={Bar}/>
<Route path='/line' component={Line}/>
</Route>
</Router>
但是发现,地址栏在变化但是页面没有变化,因为在react-router 4.0版本中不支持这种写法,而要改用以下写法
<Router history={history}>
<Switch>
<IndexPage path='/' component={IndexPage}>
<Route path='/bar' component={Bar}/>
<Route path='/line' component={Line}/>
</IndexPage>
</Switch>
</Router>
这样地址栏变化的同时也可以页面也在变化。
<Router history={history}>
<Switch>
<IndexPage path='/' component={IndexPage}>
<Route path='/bar' component={Bar}/>
<Route path='/line' component={Line}/>
<Redirect to='/bar'/>
</IndexPage>
</Switch>
</Router>
为了初始化不为空界面,可以重定向其中一个界面。
以上实现方式在页面中使用{this.props.children}来显示路由
<Sider className="site-layout-background" width={200}>
<Menus />
</Sider>
<Content style={{ padding: '0 24px', minHeight: 280 }}>
{this.props.children}
{/*<Switch>*/}
{/* <Route path="/bar" component={Bar}/>*/}
{/* <Route path='/line' component={Line}/>*/}
{/* <Redirect to='/bar'/>*/}
{/*</Switch>*/}
</Content>
当然也可可以用第二种方式,在主路由中自定义一个主页面,在展示组件中,调用上面注释的路由方式。注意在路由中不能加eact这个关键字,不然路由无法显示。
实例代码:测试代码