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