0

我正在为 Django 应用程序创建前端。我想将我的应用程序组件路由到以下。

/
/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
4

1 回答 1

1

Dashboard组件有子(嵌套)路由时,您需要exact从路由中删除:/dashboard

<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,则仅当路径与 location.pathname 完全匹配时才会匹配。

因此,当您在浏览器中添加exact/dashboard点击/dashboard/some-child-route时,它​​与Dashboard路由不匹配,并且不会呈现它及其子路由。

这篇文章也将帮助您理解它。

于 2020-05-10T14:26:26.010 回答