我正在为Django应用程序创建Frontend。我想将我的应用程序组件路由到下面。
/
/dashboard
/about
/contact
然后仪表板组件应按
进行布线/dashboard/
/dashboard/notification/
/dashboard/profile/
我成功将我的App组件路由为
import React, { Component, Fragment } from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom'
import HomeMain from './layout/main/HomeMain'
import './css/style.css'
import Notfound from './layout/main/Notfound'
import Dashboard from './layout/dashboard/Dashboard'
class App extends Component {
render() {
return (
<Router>
<Fragment>
<Switch>
<Route exact path="/dashboard" component={Dashboard} />
<Route exact path="/" component={HomeMain} />
<Route exact path="/not" component={Notfound} />
</Switch>
</Fragment>
</Router>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
然后,我尝试使用嵌套路由来路由我的仪表板,但是输出在 http://127.0.0.1:8000/dashboard/notification/
处变成空白页import React, { Fragment } from 'react'
import '../../css/dash.css'
import '../../css/style.css'
import DashHeader from './DashHeader'
import DashMain from './Dmain/DashMain'
import NotiMain from './Dmain/NotiMain'
import { Switch, Route, BrowserRouter as Router } from 'react-router-dom'
class Dashboard extends React.Component {
path = this.props.match.path
render() {
return (
<Fragment>
<DashHeader />
<Switch>
<Route exact path={`${this.path}/`}>
<DashMain />
</Route>
<Route exact path={`${this.props.match.url}/notification`}>
<DashMain />
</Route>
</Switch>
</Fragment>
)
}
}
export default Dashboard
答案 0 :(得分:1)
当仪表板组件具有子(嵌套)路由时,您需要从/dashboard
路由中删除exact
:
<Router>
<Fragment>
<Switch>
<Route path="/dashboard" component={Dashboard}/> // remove exact
<Route exact path="/" component={HomeMain}/>
<Route exact path="/not" component={Notfound}/>
</Switch>
</Fragment>
</Router>
来自文档:
为true时,仅在路径与位置匹配时才匹配。 完全是
因此,当您在exact
添加/dashboard
并在浏览器中点击 / dashboard / some-child-route 时,它与 Dashboard < / strong>路由,并且不渲染它及其子级。
This帖子也会帮助您理解。