反应嵌套路由无法正常工作

React nested routing not working properly

我正在为 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

Dashboard 组件有子(嵌套)路由时,您需要从 /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>

来自文档:

When true, will only match if the path matches the location.pathname exactly.

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

post也会帮助你理解。