在我的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时隐藏标题。 最好的解决方案是什么?
答案 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
希望有帮助!