在React-Router的Not Found页面上隐藏公共组件

时间:2019-09-23 10:41:39

标签: reactjs react-router

在我的react应用程序中,有一个通用标头位于我的Routes之外,并且其他组件是根据路由加载的。

      <React.Fragment>
            <Header />
            <div className="container dflex">
              <Switch>
                <Route path="/money-transfer" component={MoneyTransfer} />
                <Redirect from="/" to="/money-transfer" exact />
                <Route path="/dmt" exact component={MyDmt} />
                <Route component={NoFound} />
              </Switch>
          </div>
      </React.Fragment>

我还想在呈现NoFound Page时隐藏标题。 最好的解决方案是什么?

2 个答案:

答案 0 :(得分:2)

尝试一下

  <React.Fragment>
                 let HideHeader = NoFound ? null : <Header />
                 {HideHeader}
                <div className="container dflex">
                  <Switch>
                    <Route path="/money-transfer" component={MoneyTransfer} />
                    <Redirect from="/" to="/money-transfer" exact />
                    <Route path="/dmt" exact component={MyDmt} />
                    <Route component={NoFound} />
                  </Switch>
              </div>
          </React.Fragment>

答案 1 :(得分:1)

当没有路由匹配时,您可以Redirect到特定的路由,然后在Header中检查该路由以隐藏该组件。

 <Switch>
    <Route path="/money-transfer" component={MoneyTransfer} />
    <Redirect from="/" to="/money-transfer" exact />
    <Route path="/dmt" exact component={MyDmt} />
    <Route component={NoFound} />
 </Switch>

function NoFound() {
  return <Redirect to="/notfound" />;
}

// Header.js

const Header = props => {
  const { location } = props;

  if (location.pathname.match(/notfound/)) {
    return <NotFoundRoute />;
  }
  return <h3>I am the Header</h3>;
};

export default withRouter(Header);

// NotFoundRoute.js

function NotFoundRoute() {
  return <div>No Route Found</div>;
}

工作代码示例codesandbox link

希望有帮助!