首页 > 解决方案 > React-Router:始终显示标题但不在登录页面中

问题描述

我当前的路由器树如下所示:

  <Route exact path="/" component={Landing} />
  <Route component={Header} />§
  <Route path="/component1" component={Component1} />
  <Route path="/component2" component={Component2} />
  ...

我希望<Header />在渲染组件时始终显示<Component1 /><Component2 />而不是在用户位于登录页面 ( <Landing />) 时显示。

但是,对于上面的反应路由器树,<Header />总是显示。

标签: reactjsreact-routerreact-router-v4

解决方案


您可以使用Switchfromreact-router-dom并配置您的路线,例如

<Switch>
    <Route exact path="/" component={Landing} />
    <Route component={Header} />
</Switch>
<Route path="/component1" component={Component1} />
<Route path="/component2" component={Component2} />

在上述情况下,如果Landing路由匹配,Header则不渲染,否则Header渲染


推荐阅读