在布局中反应路由器 4 和路径参数

React router 4 and path params in layouts

我无法理解如何在布局组件中通过 React Router 4 访问路径参数。

系统有管理项目的页面,可以通过包含项目id的路径访问,例如/projects/1/projects/2等。 还有其他非项目页面使用相同的布局,例如 /settings.

该布局在页面顶部呈现一个导航栏,如果选择了一个项目,该导航栏应包含一个项目菜单。 IE。项目菜单应显示在 /projects/:projectId,而不是 /settings

这是我要实现的目标的简化版本: https://codesandbox.io/s/18vm42n417

感谢任何帮助!

这是来自 codesandbox.io link:

的代码
import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter, Route, Switch, Link } from 'react-router-dom'

const ProjectMenu = () => (
  <div>
    Project menu<br />
    <small>(should only be visible on project pages)</small>
  </div>
)

const NavBar = () => (
  <div style={{
    backgroundColor: 'deepPink',
    padding: 32
  }}>
    {/*
      How can I check for the projectId path param here
      and render the project menu only if it is set?
      Note that the /settings page should not have
      the project menu.
    */}
    <ProjectMenu />
  </div>
)

const Layout = ({ children }) => (
  <div style={{
    backgroundColor: 'hotPink',
  }}>
    <NavBar />
    <div style={{
      padding: 64
    }}>
      {children}
    </div>
  </div>
)

const Start = () => (
  <div>
    <Link to='/projects/1'>Project 1</Link><br />
    <Link to='/projects/2'>Project 2</Link><br />
    <Link to='/settings'>Settings</Link>
  </div>
)

const Project = ({match}) => (
  <div>
    Project {match.params.projectId}<br /><br />
    <Link to='/'>Back</Link>
  </div>
)

const Settings = () => (
  <div>
    Settings<br /><br />
    <Link to='/'>Back</Link>
  </div>
)

const App = () => (
  <BrowserRouter>
    <Layout style={{ padding: 64 }}>
      <Switch>
        <Route path='/projects/:projectId' component={Project} />
        <Route path='/settings' component={Settings} />
        <Route path='/' component={Start} />
      </Switch>
    </Layout>
  </BrowserRouter>
)

render(
  <App />,
  document.getElementById('root')
)

这是你想做的吗?

 const NavBar = () => (
      <div style={{
        backgroundColor: 'deepPink',
        padding: 32
      }}>
        {/*
          How can I check for the projectId path param here
          and render the project menu only if it is set?
          Note that the /settings page should not have
          the project menu.
        */}
        <Route path='/projects/:projectId' component={ProjectMenu} />
      </div>
    )

并且您可以通过这种方式获得projectID。

const ProjectMenu = ({ match }) => (
  <div>
    Project menu<br />
    <small>(should only be visible on project pages)</small>
    {match.params.projectId}
  </div>
);