【问题标题】:How to do nested routes with react router 4?如何使用反应路由器 4 进行嵌套路由?
【发布时间】:2017-03-30 16:42:08
【问题描述】:

有谁知道如何在反应路由器 4 中进行嵌套路由?我想这样设置路线:

import React from 'react';
import { Route, Switch } from 'react-router';

import Containers from './containers/index';
import Components from './components/index';

export default (
    <Switch>
      <Route path='/users' component={Containers.Users} />
      <Route path='/users/:id' component={Containers.User} />
    </Switch>
)

但是/tickets/:id 继续默认为Containers.Users 呈现的组件——而不是来自Containers.User 的组件。我通过一个非常简单的设置就可以使用 react-router 3,但似乎发生了很多变化:

<Route path="/users" component={Containers.Users}>
  <Route path="/users/:id" component={Containers.User}/>
</Route >

有谁知道像上述 react-router 4 这样非常简单的嵌套路由模式的最新设置?

【问题讨论】:

标签: reactjs redux react-router


【解决方案1】:

现在在 v4 中,您应该在父组件中添加路由,不再需要嵌套路由。

    <Redirect from="/courses/" to="/courses/html" />
    <Switch>
        <Route path="/courses/html" component={HTML} />
        <Route path="/courses/css" component={CSS} />
        <Route path="/courses/javascript" component={JavaScript} />
    </Switch>

在这里找到这个https://teamtreehouse.com/community/warning-you-should-not-use-route-component-and-route-children-in-the-same-route-route-children-will-be-ignored

【讨论】:

  • 非常感谢先生!
【解决方案2】:

我今天早些时候在使用 React Router v4 时遇到了同样的问题,这解决了我的问题

<Route exact path="/users" component={Containers.Users/>
<Route path="/users/:id" component={Containers.Users />

在这种情况下,/users 是您的路由的基本路径,/users/:id 是子路径,因此您需要为父路由指定确切的路径。

【讨论】:

    猜你喜欢
    • 2019-02-18
    • 2016-08-18
    • 1970-01-01
    • 2020-01-04
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 2015-11-25
    相关资源
    最近更新 更多