66

我正在尝试设置一些嵌套路由来添加通用布局。检查代码:

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

虽然这工作得很好,但我仍然收到警告:

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

4

5 回答 5

83

CESCO 的答案首先呈现组件,AppShell 然后呈现其中的一个组件 Switch。但是这些组件不会在内部渲染AppShell,它们不会是AppShell.

在 v4 中,为了包装组件,您不再将Routes 放入 anotherRoute中,而是将Routes 直接放入组件中。
IE:对于包装器而不是<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组件,因为它在这里没有用。看看这里什么时候有用。

于 2017-03-10T16:40:28.720 回答
10

您需要使用 switch 组件进行嵌套才能正常工作。另外,看到这个问题

// 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 组件不带子组件,相反,您应该使用 render 道具。

<Router>
    <Route render={(props)=>{
      return <div>Whatever</div>}>
    </Route>
  </Router>
于 2017-02-16T15:54:56.003 回答
5

尝试:

<Router>
    <Layout>
        <Route path='/abc' component={ABC} />
        <Route path='/xyz' component={XYZ} />
    </Layout>
</Router>
于 2017-03-01T22:04:21.303 回答
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 就会运行

于 2017-08-21T13:45:02.840 回答
0

你也可以试试这个:

<Route exact path="/Home"
                 render={props=>(
                                 <div>
                                      <Layout/>
                                      <Archive/>
                                </div>
                       )} 
    />
于 2017-12-31T07:50:26.620 回答