【问题标题】:React router - Nested routes not working反应路由器 - 嵌套路由不起作用
【发布时间】:2015-11-25 00:20:35
【问题描述】:

我的目标是让http://mydomain/route1 渲染 React 组件 Component1 和 http://mydomain/route2 渲染 Component2。因此,我认为编写如下路线是很自然的:

    <Route name="route1" handler={Component1}>
        <Route name="route2" handler={Component2} />
    </Route>

    <DefaultRoute name="home" handler={Home} />
  </Route>

http://mydomain/route1 按预期工作,但 http://mydomain/route2 会呈现 Component1。

然后我阅读this question并将路由更改为:

    <Route name="route1" path="route1" handler={Component1} />
    <Route name="route2" path="route1/route2" handler={Component2} />

    <DefaultRoute name="home" handler={Home} />
  </Route>

http://mydomain/route2http://mydomain/route2 现在都按预期工作。但是,我不明白为什么前一个在我看来更合乎逻辑和更整洁时不起作用。

嵌套语法适用于“/”和“route1”,那么为什么不适用“route1”和“route2”呢?

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    问题在于,在嵌套路由中,路由器会尝试挂载与层次结构匹配的所有组件。当您想将组件相互嵌套时,这是最好的使用......但是如果您想要两个单独的路由来匹配不同的组件,它们将需要是它们自己的路由。

    <Route handler={App}>
      <Route path="route1" handler={Component1} />
      <Route path="/route1/route2" handler={Component2} />
      <DefaultRoute name="home" handler={Home} />
    </Route>
    

    当 URL 为 /route1/route2 时,Component2 将挂载(在App 内部)。

    如果您想嵌套组件,您需要将&lt;RouteHandler/&gt; 添加到Component1,以便在其中呈现Component2

    之所以可行,是因为嵌套组件与嵌套 URL 不同,可以由路由器单独处理。有时您希望组件嵌套但不一定是 URL,反之亦然。

    【讨论】:

    • 很好,简洁的解释。谢谢!
    【解决方案2】:

    当使用需要正确活动状态的导航的分层路由时,更好的方法是执行以下操作(使用 RR2 的语法):

    <Route path="route1">
        <IndexRoute component={Component1}/>
        <Route path="route2" component={Component2} />
     </Route>
    

    这样,当 URL 为 /route1/route2 时,route1 的任何导航链接都将正确地处于活动状态。

    【讨论】:

      【解决方案3】:

      我正在解决类似的问题(Component2 未渲染)并且嵌套路由不起作用,因为我忘记在 Component1 中渲染 {this.props.children}

      【讨论】:

        猜你喜欢
        • 2017-10-27
        • 2019-02-18
        • 1970-01-01
        • 1970-01-01
        • 2016-08-18
        • 1970-01-01
        • 2019-01-12
        • 2017-08-06
        • 1970-01-01
        相关资源
        最近更新 更多