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

时间:2017-03-16 22:20:04

标签: javascript reactjs react-router react-router-v4

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

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

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

  

警告:您不应该使用&lt; Route&gt;组件和&lt;路由子&gt;在同一条路线上; &lt;路线儿童&gt;将被忽略

这里到底发生了什么?我已经搜索了the docs几个小时,无法成功获得嵌套路由。如何使用<Route> 组件将其路由嵌套在react-router v4中?我的简单示例如何转换为嵌套路由的v4.x API合规性?

2 个答案:

答案 0 :(得分:11)

忘掉你对React Router的了解&lt; 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

答案 1 :(得分:0)

With react-router v4 and v5 you can also use the render prop to nest routes

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

In my opinion this syntax ends up more readable in most situations, compared to splitting out the sub-routes into a separately defined component passed in through the component prop.

I posted a similar answer here but noticed this question also has a lot of views and so thought it would be helpful to port it here.