如何在嵌套路由中渲染组件

时间:2021-06-18 09:38:06

标签: javascript reactjs react-router-dom

我在下面有沙箱:

Edit Responsive - antd@4.16.3 (forked)

当前顶级导航按预期工作,但是当我尝试嵌套 sub routes 时,它不会呈现我的 Item1 组件。有什么我想念的吗。我试图将 Item 包装在 nav3 路径中,但这也不起作用。

  <Layout>
        <Header
          className="site-layout-sub-header-background"
          style={{ padding: 0 }}
        />
        <Content style={{ margin: "24px 16px 0" }}>
          <div
            className="site-layout-background"
            style={{ padding: 24, minHeight: 360 }}
          >
            <Switch>
              <Route path="/nav1" component={nav1} />
              <Route path="/nav2" component={nav2} />
              <Route path="/nav3" component={nav3} />
              <Route path="/nav3/item1" component={item1} />
            </Switch>
          </div>
        </Content>
        <Footer style={{ textAlign: "center" }}>
          Ant Design ©2018 Created by Ant UED
        </Footer>
      </Layout>

2 个答案:

答案 0 :(得分:0)

您只需在 exact 中添加 Route

<Route exact path="/nav3" component={nav3} />
<Route exact path="/nav3/item1" component={item1} />

答案 1 :(得分:0)

您需要将 exact={true} 道具添加到您的 /nav3 路线中,如下所示。

<Route path="/nav3" component={nav3} exact={true}/>

如果您不向 exact 组件添加 Route,则每个以 /nav3 开头的网址都将呈现 nav3 组件。

<块引用>

exact: bool 当为真时,仅当路径匹配时才匹配 location.pathname 准确。

您可以阅读有关确切道具 here

的更多信息