为什么不能在react-router中嵌套Route组件4.x?

Why can I not nest Route components in react-router 4.x?

如何在 react-router 中使用嵌套路由,特别是版本 4.x?以下在以前的版本中运行良好...

<Route path='/stuff' component={Stuff}>
  <Route path='/stuff/a' component={StuffA} />
</Route>

升级到 4.x 会引发以下警告...

Warning: You should not use <Route> component and <Route children> in the same route; <Route children> will be ignored

这到底是怎么回事?我已经搜索了 the docs 几个小时,但无法成功使嵌套路由正常工作。如何使用 <Route>components 将他们的路由嵌套在 react-router v4 中?我的简单示例如何转换为 v4.x API 嵌套路由的合规性?

忘记你对 React Router < v4 的了解。您通过逐字嵌套 <Routes> 来嵌套路由。检查 this example。具体检查主题组件。您无需预先声明路由,而是在组件呈现时动态声明。

import React from 'react'
import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom'

const BasicExample = () => (
  <Router>
    <div>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/about">About</Link></li>
        <li><Link to="/topics">Topics</Link></li>
      </ul>

      <hr/>

      <Route exact path="/" component={Home}/>
      <Route path="/about" component={About}/>
      <Route path="/topics" component={Topics}/>
    </div>
  </Router>
)

const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
)

const About = () => (
  <div>
    <h2>About</h2>
  </div>
)

const Topics = ({ match }) => (
  <div>
    <h2>Topics</h2>
    <ul>
      <li>
        <Link to={`${match.url}/rendering`}>
          Rendering with React
        </Link>
      </li>
      <li>
        <Link to={`${match.url}/components`}>
          Components
        </Link>
      </li>
      <li>
        <Link to={`${match.url}/props-v-state`}>
          Props v. State
        </Link>
      </li>
    </ul>

    {/* NESTED ROUTES */}
    <Route path={`${match.url}/:topicId`} component={Topic}/>
    <Route exact path={match.url} render={() => (
      <h3>Please select a topic.</h3>
    )}/>
  </div>
)

const Topic = ({ match }) => (
  <div>
    <h3>{match.params.topicId}</h3>
  </div>
)

export default BasicExample

使用 react-router v4v5 你也可以使用 render 属性来嵌套路由

<Route 
  path='/stuff' 
  render={({ match: { url } }) => (
    <>
      <Route path={`${url}/`} component={Stuff} exact />
      <Route path={`${url}/a`} component={StuffA} />
    </>
  )} 
/>

在我看来,与将子路由拆分为通过 component prop 传入的单独定义的组件相比,这种语法在大多数情况下最终更具可读性。

我发布了一个 但注意到这个问题也有很多观点,所以认为将它移植到这里会有所帮助。