首页 文章

React Router v4中的嵌套路由

提问于
浏览
62

我正在尝试设置一些嵌套路由来添加公共布局 . 检查代码:

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

虽然这很好用,但我仍然收到警告:

警告:您不应在同一路线中使用<Route component>和<Route children>;将被忽略

5 回答

  • 78

    你也可以试试这个:

    <Route exact path="/Home"
                     render={props=>(
                                     <div>
                                          <Layout/>
                                          <Archive/>
                                    </div>
                           )} 
        />
    
  • 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

    尝试:

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

    CESCO的答案首先在 Switch 中呈现组件 AppShell then 组件之一 . 但是这些组件不会在 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 组件,因为's not useful here. See when it'有用here .

  • 0

    您需要使用开关组件进行嵌套才能正常工作 . 另外,看到这个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>
    

相关问题