React路由器仅显示没有在我的浏览器中定义的组件的路由 [英] React router show only route without components defined in my browser

查看:44
本文介绍了React路由器仅显示没有在我的浏览器中定义的组件的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,在我的路线文件中,我设置了我的结构标题导航栏还有我的开关脚

const AppRouter = () =>(<浏览器路由器><Route path="/login" component={AuthPage} exact={true}/><Route path="/dashboard/addProduct" component={AddProduct}精确={true}/><div><标题/><导航/><容器 maxWidth="lg" ><开关><Route path="/" component={LandingPage} exact={true}/><Route path="/xd" component={AuthPage} exact={true}/><路由组件={NotFoundPage}/></开关></容器>

</BrowserRouter>);

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

分别是 login 和 addproduct 路由

我怎么能这样做?

解决方案

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

从react"导入React;import { withRouter } from "react-router-dom";const 导航 = 道具 =>{const { 位置 } = 道具;const { 路径名 } = 位置;if (pathname !== "/login" || pathname !== "/dashboard/addProduct" ) {返回 (//组件逻辑在这里);}//如果我们在这些路线上,我们应该返回 null 以不渲染任何东西返回空;};导出默认 withRouter(Navigation);

如果您想要更稳健的长期方法,此答案可能会有所帮助:如何在反应路由器的登录页面中隐藏导航栏

Hello in my directions file I set my struct header navbar and my switch foote

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>
);

But I have two routes where I didn't want to show my header footer and nav bar

which are the login and addproduct routes

how could i do that?

解决方案

This is a little bit hacky (just to match your current approach) since I'm assuming you just want to hide those components in only those 2 routes, You can use withRouter in your Header and Navigation components, withRouter will provide to you the location prop and you can have a condition like this:

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);

If you want a more robust long term approach this answer could help: How to hide navbar in login page in react router

这篇关于React路由器仅显示没有在我的浏览器中定义的组件的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆