简体   繁体   English

渲染路线条件渲染。 反应路由器(hashrouter)

[英]Render route conditional rendering. React router (hashrouter)

I'm using Hashrouter component of React Router to render my different routes in a React application. 我正在使用React Router的Hashrouter组件在React应用程序中渲染我的不同路由。 In order to avoid duplicating code, I created a couple of components called TopBar and Footer, as the name suggests it renders this two elements in the website. 为了避免重复代码,我创建了几个名为TopBar和Footer的组件,顾名思义,它在网站中呈现了这两个元素。 My problem comes when I want to add another route for an admin page which I DON'T WANT to have TopBar neither Footer. 当我想为管理页面添加另一条我不想让TopBar和Footer都不添加的路由时,我的问题就来了。 Since the path is matching with '/' it is obviously showing both components along with the AdminFrame component. 由于该路径与“ /”匹配,因此显然会显示这两个组件以及AdminFrame组件。

I have a couple of workaround solutions in mind but I would like to know if there's any plain and easy solution to this problem without changing any route in this structure: 我有几个解决方法,但我想知道是否有解决此问题的简单方法,而无需更改此结构中的任何路由:

<HashRouter>
  <div>
    <Route path="/" render={()=> (
      <TopBar/>
    )} />
    <Route exact path="/" render={() => (
      <Home />
    )} />
    <Route exact path="/contacto" render={() => (
      <Contact />
    )} />
    <Route path="/" render={()=> (
      <Footer/>
    )} />
    <Route path="/admin" render={()=> (
      <AdminFrame/>
    )} />
  </div>
</HashRouter>

Any help appreciated. 任何帮助表示赞赏。

If the Topbar and Footer is shown only on the homepage, you might consider just putting TopBar and Footer somewhere in the Home component instead. 如果Topbar和Footer仅显示在主页上,则可以考虑将TopBar和Footer放在Home组件中的某个位置。 If you still need the Topbar and Footer i'd go with a Switch to organize the routes better: 如果您仍然需要Topbar和Footer,则可以使用Switch更好地组织路线:

<HashRouter>
  <div>
    <Route exact path="/" render={()=> (
      <TopBar/>
    )} />
    <Route exact path="/" render={()=> (
      <Footer/>
    )} />
    <Switch>
        <Route path="/contacto" render={() => (
          <Contact />
        )} />
        <Route path="/admin" render={()=> (
          <AdminFrame/>
        )} />
        <Route path="/" render={() => (
          <Home />
        )} />
    </Switch>
  </div>
</HashRouter>

Switch renders only the first matching route. Switch仅呈现第一个匹配的路由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM