当前位置 : 主页 > 网页制作 > React >

reactjs – 在React-Router v3中,所有路由必须嵌套在with path =“/”中吗?

来源:互联网 收集:自由互联 发布时间:2021-06-15
我问这个是因为我想知道这个(下面)是否可行,如果是这样的话,我的页面应该如何正常工作呢? Router history={browserHistory} Route path="/" component={Root} IndexRoute component={Home} / Route path="404" comp
我问这个是因为我想知道这个(下面)是否可行,如果是这样的话,我的页面应该如何正常工作呢?

<Router history={browserHistory}>
    <Route path="/" component={Root}>
        <IndexRoute component={Home} />
        <Route path="404" component={Empty} />
        <Route path="about" component={About} />
        <Route path="archive" component={Archive} />
        <Redirect from="*" to="/404" />
    </Route>
    <Route path="dashboard" component={_Dashboard}>
        <IndexRoute component={_Master} />
        <Route path="post" component={_Post} />
        <Redirect from="*" to="/dashboard" />
    </Route>
</Router>

是否可以让“/”和“仪表板”的路线成为彼此相同级别的孩子?

出于布局目的,我希望嵌套在“/”下的所有页面都使用Root组件的布局,而所有嵌套在“dashboard”下的页面都使用_Dashboard组件的布局.

更新(下面的解决方案)

使我上面的工作无法工作/可能的问题是由于我的根目录的Redirect所在的位置.以下Thomas Sojka的回答解决了我的问题.

这里(下面)是我目前所拥有的,正如我需要的那样(这次组件名称和路径略有不同,但总体思路和结构应足以显示解决方案).

<Router history={browserHistory}>
    <Route path="/" component={Root}>
        <IndexRoute component={Home} />
        <Route path="404" component={Empty} />
        <Route path="about" component={About} />
        <Route path="archive" component={Archive} />
    </Route>
    <Route path="dashboard" component={_Root}>
        <IndexRoute component={_Home} />
        <Route path="404" component={_Empty} />
        <Route path="post" component={_Post} />
        <Route path="post-single" component={_PostSingle} />
        <Redirect from="*" to="404" />
    </Route>
    <Redirect from="*" to="404" />
</Router>

根级别的重定向必须与“/”和“仪表板”的路由相同,并且在所有这些路由之后/之下才能工作.我在原始问题中找到了这个重定向的地方,以便“仪表板”及其任何一个孩子都找不到.

对“仪表板”的任何子项进行重定向也位于其中.

您需要将404路由放在最后,否则永远不会找到/ dashboard路由:

<Router history={browserHistory}>
    <Route path='/' component={Root}>
      <IndexRoute component={Home} />
      <Route path='404' component={Empty} />
      <Route path='about' component={About} />
      <Route path='archive' component={Archive} />
    </Route>
    <Route path='/dashboard' component={_Dashboard}>
      <IndexRoute component={_Master} />
      <Route path='post' component={_Post} />
      <Redirect from='*' to='/dashboard' />
    </Route>
    <Redirect from='*' to='/404' />
  </Router>
网友评论