如何只为一条路线渲染组件?

时间:2018-11-12 15:10:31

标签: reactjs routing react-router

我正尝试仅从路线页面中删除 Header 组件。我该如何在React Router 4中做到这一点?

这是我的路线

const AppRouter: any = () => (
      <BrowserRouter>
        <React.Fragment>
          <Header />
          <Switch>
            <Route path={LOOP_MAIN_ROUTE} component={LandingPage} exact/>
            <Route path={LOOP_LOGIN_ROUTE} component={LoginPage} exact/>
            <ProtectedRoute path={LOOP_SEARCH_ROUTE} component={SearchPage} />
            <ProtectedRoute path={LOOP_OFFER_ROUTE} component={Offer} exact />
            <ProtectedRoute path={LOOP_OFFER_APPROVAL} component={OfferApproval} exact />
            <ProtectedRoute path={LOOP_OFFER_CONFIRMATION} component={OfferConfirmation} exact />
          </Switch>
        </React.Fragment>
      </BrowserRouter>
    );

export default AppRouter;

2 个答案:

答案 0 :(得分:2)

Header可以有条件地呈现为路线:

<Route render={
  ({ location: { pathname } }) => pathname !== LOOP_MAIN_ROUTE && <Header/>
}/>

答案 1 :(得分:1)

一种方法是使用matchPath。例如在您的Header组件中:

import React from "react";
import {LOOP_MAIN_ROUTE} from "whereverYouHaveThisConstant";
import { withRouter, matchPath } from 'react-router-dom';
const Header = (props) => {
   const suppressHeader = matchPath(props.location.pathname, {path: LOOP_MAIN_ROUTE});
   if (suppressHeader ) {
      return null;
   }
   return <>your header stuff</>;
};
export default withRouter(Header);