【问题标题】:Render components for all routes except one specific route为除一条特定路线之外的所有路线渲染组件
【发布时间】:2019-10-18 00:38:11
【问题描述】:

我正在编写一个具有多个路由的 React 应用程序,我还有页眉和页脚组件,它们在所有组件上都是可见的。但现在我想隐藏特定路线的页脚组件。

<Header />
        <Switch>
          <Route path={routes.home} exact component={Home} />
          <Route path={routes.office} component={Office} />
          <Route path={routes.park} exact component={Park} />
          ...
          ...
          ...
          <Route path={routes.shopping} component={Shopping} />
        </Switch>
    <Footer />

所以页眉和页脚组件总是被渲染。但是现在我希望除购物之外的所有路线都可以看到页脚组件,我该怎么做?

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    不使用渲染道具或 useRouteMatch 钩子的最佳方法是对不需要页眉或页脚的页面使用一个特定路由,并使用“包罗万象” " 将匹配所有其他路由的路由。然后,您可以使用嵌套的 Switch 语句来处理其余的应用程序路由。

    在下面的示例中,我有一个 '/auth' 路由,它只会呈现 Auth 组件而不会呈现其他任何内容。在应用程序的其余部分(用户登录后),我希望导航栏和侧边栏组件显示在所有路线上,因此它们位于没有设置“路径”属性的“全能”路线内。这意味着它将触发除 '/auth' 之外的所有路由(因为 /auth 在它之前声明)。

    <Router>
      <div className="App">
        <Switch>
          {/* The route which will not render the sidebar and navbar components */}
          <Route path="/auth">
            <Auth/>
          </Route>
          {/* Catch-all route that will match everything except /auth and render Sidebar and Navbar on all pages */}
          <Route>
            <Sidebar/>
            <Navbar/>
            {/* The rest of the routes for the application */}
            <Switch>
              <Route exact path="/">
                <Home/>
              </Route>
              <Route path="/about">
                <About/>
              </Route>
              <Route path="/projects">
                <Projects/>
              </Route>
            </Switch>
          </Route>
        </Switch>
      </div>
    </Router>
    

    【讨论】:

      【解决方案2】:

      有几种方法可以做到这一点,一种方法是:

      首先通过props将要隐藏的路由作为数组传递:

      <Router>
          <Header hideRoutes={[routes.shopping]} />
          <Switch>
              <Route path={routes.home} exact component={Home} />
              <Route path={routes.office} component={Office} />
              <Route path={routes.park} exact component={Park} />
              {/*moreRoutes*/}
              <Route path={routes.shopping} component={Shopping} />
          </Switch>
          <Footer hideRoutes={[routes.shopping]} />
      </Router>
      

      然后在你的页眉和页脚组件中检查隐藏路径的路径名,然后在适当的时候通过传回一个空的 div 来隐藏

      const Header = (props)=>{
          const {hideRoutes , location:{pathname}} = props
          let shouldHide = false
          hideRoutes.some(hideRoute => {
              if (pathname === hideRoute)
                  return shouldHide = true
          })
          if (shouldHide) 
              return <div/>
      
          //proceed to return header
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-25
        • 1970-01-01
        • 1970-01-01
        • 2018-12-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多