React Router v4中的嵌套路由

时间:2017-02-07 16:55:29

标签: react-router react-router-v4

我试图设置一些嵌套路线来添加公共布局。检查代码:

<materials>
        <est_mat>
          <pos>20</pos>
          <item>BOX</item>
          <qty>0.004</qty>
        </est_mat>
    <est_mat>
          <pos>30</pos>
          <item>xxx-xxx-xxx01</item>
          <qty>1</qty>
        </est_mat>
    <est_mat>
          <pos>40</pos>
          <item>xxx-xxx-xxx02</item>
          <qty>1</qty>
        </est_mat>
</materials>

虽然这完全正常,但我仍然收到警告:

  

警告:您不应该使用&lt; Route component&gt;和&lt;路线儿童&gt;在相同的   路线;将被忽略

5 个答案:

答案 0 :(得分:80)

CESCO的回答首先呈现AppShell 组件{<1}} 组件Switch中的一个组件。但是这些组件不会在AppShell内呈现,它们不会是AppShell的子项。

在v4中打包组件时,您不再将Route放在另一个Route内,而是将Route直接放在组件内。
I.E:对于包装而不是<Route component={Layout}>,您直接使用<Layout>

完整代码:

  <Router>
    <Layout>
      <Route path='/abc' component={ABC} />
      <Route path='/xyz' component={XYZ} />
    </Layout>
  </Router>

这种变化可能是因为让React Router v4变得纯粹的想法 React所以你只使用React元素和任何其他React元素。

编辑:我删除了Switch组件,因为它在这里没用。查看它何时有用here

答案 1 :(得分:9)

您需要使用开关组件进行嵌套才能正常工作。另请参阅此question

// main app
<div>
    // not setting a path prop, makes this always render
    <Route component={AppShell}/>
    <Switch>
        <Route exact path="/" component={Login}/>
        <Route path="/dashboard" component={AsyncDashboard(userAgent)}/>
        <Route component={NoMatch}/>
    </Switch>
</div>

版本4组件不带孩子,相反,你应该使用渲染道具。

<Router>
    <Route render={(props)=>{
      return <div>Whatever</div>}>
    </Route>
  </Router>

答案 2 :(得分:5)

尝试:

<Router>
    <Layout>
        <Route path='/abc' component={ABC} />
        <Route path='/xyz' component={XYZ} />
    </Layout>
</Router>

答案 3 :(得分:2)

如果您不希望Layout在加载时运行。使用此方法:

<div className="container">
    <Route path="/main" component={ChatList}/>
    <Switch>
        <Route exact path="/" component={Start} />
        <Route path="/main/single" component={SingleChat} />
        <Route path="/main/group" component={GroupChat} />
        <Route path="/login" component={Login} />
    </Switch>
</div>

每当历史记录发生变化时,ChatList中的 componentWillReceiveProps 都会运行。

答案 4 :(得分:0)

你也可以试试这个:

<Route exact path="/Home"
                 render={props=>(
                                 <div>
                                      <Layout/>
                                      <Archive/>
                                </div>
                       )} 
    />
相关问题