react-router 4 路由的嵌套
1.在component组件内部需要嵌套的位置直接嵌套Route标签
这个方法会使得路由标签比较分散,子组件我们必须直接将Route标签写入到父组件之中,而且路由必须包含根路径.
// Dashboard.jsx
import Menu from '~/components/Menu/Menu';
import React from 'react';
import {Route,Switch} from "react-router-dom";
import Index from '~/container/Index/Index';
import TaskList from '~/container/TaskManage/TaskList/TaskList'
const routes = [
{
path: "/Dashboard/Index",
component: Index
},
{
path: "/Dashboard/TaskManage/TaskList",
component: TaskList
}
];
class Dashboard extends React.Component{
constructor(props, context ) {
super(props, context );
}
render(){
return(
<div>
<Menu/>
<div className='container'>
<div>
{routes.map((route, index) => (
<Route
exact
key={index}
path={route.path}
component={route.component}
/>
))}
</div>
</div>
</div>
)
}
}
export default Dashboard
2.使用Route render渲染作内联嵌套
component使用this.props.children进行嵌套渲染,Dashboard为父组件,Index和TaskList为子组件
// router.js
<Router history={history}>
<Switch>
<Route exact path="/" component={Login}/>
<Route path="/" render={({history,location,match}) => (
<Dashboard history={history} location={location} match={location}>
<Route path="/Dashboard/Index" component={Index}></Route>
<Route path="/Dashboard/TaskManage/TaskManageIng" component={TaskManageIng}></Route>
<Route path="/Dashboard/TaskManage/TaskList" component={TaskList}></Route>
<Route path="/Dashboard/TaskManage/TaskResource" component={TaskResource}></Route>
</Dashboard>
)} />
</Switch>
</Router>
// Dashboard.jsx
import Menu from '~/components/Menu/Menu';
import React from 'react';
class Dashboard extends React.Component{
constructor(props, context ) {
super(props, context );
}
render(){
return(
<div>
<Menu/>
<div className='container'>
<div>
{this.props.children}
</div>
</div>
</div>
)
}
}
export default Dashboard