【问题标题】:React router show only route without components defined in my browserReact 路由器仅显示没有在我的浏览器中定义的组件的路由
【发布时间】:2020-04-05 05:03:48
【问题描述】:

您好,在我的路线文件中,我设置了我的结构 标题 导航栏 和我的开关 脚注

const AppRouter = () => (
  <BrowserRouter>
          <Route path="/login" component={AuthPage} exact={true} /> 
          <Route path="/dashboard/addProduct" component={AddProduct} exact={true} /> 
   <div>
    <Header/>
    <Navigation/>
    <Container maxWidth="lg" >
      <Switch>
        <Route path="/" component={LandingPage} exact={true} /> 
        <Route path="/xd" component={AuthPage} exact={true} /> 
        <Route component={NotFoundPage} />
      </Switch>
      </Container>
    </div>  
  </BrowserRouter>
);

但我有两条路线不想显示我的标题 页脚 和导航栏

登录和添加产品路径

我该怎么做?

【问题讨论】:

  • 您也必须尝试将这些路由包装在 Switch 中
  • 你能帮我吗?我有点困惑。

标签: reactjs react-router


【解决方案1】:

这有点 hacky(只是为了匹配您当前的方法),因为我假设您只想在这 2 条路线中隐藏这些组件,您可以在 HeaderNavigation 中使用 withRouter组件,withRouter 将为您提供location 属性,您可以有这样的条件:

import React from "react";
import { withRouter } from "react-router-dom";

const Navigation = props => {
  const { location } = props;
  const { pathname } = location;

  if (pathname !== "/login" || pathname !== "/dashboard/addProduct" ) {
   return (
     // Component logic goes here
   );
  }
  // if we're on those routes we should return null to not render anything
  return null;
};

export default withRouter(Navigation);

如果您想要更稳健的长期方法,此答案可能会有所帮助: How to hide navbar in login page in react router

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 2021-10-09
    • 2018-09-13
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多