如何在登录或注册页面中隐藏导航栏反应路由器

时间:2017-09-21 11:25:30

标签: reactjs react-redux react-router-v4

我正在使用react-router v4我正在使用它来创建SPA,因此我的导航菜单会出现在所有页面中,但我不希望它出现在我的登录或注册页面中。 无论如何要做到这一点?我使用localStorage,但由于它始终隐藏

我的路线中的

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter basename="/sephoraweb">
      <div>
        <HeaderContainer />


        <Route exact path="/" component={LoginContainer} hideNavBar={true} />
        <Route path="/signUp" component={SignUpContainer} />

      </div>
    </BrowserRouter>
 </Provider>,
  document.getElementById('root')
);

以下是我的导航栏代码

 render() {
    if (!this.props.programList) {
      return <Spinner name="circle" />;
    }
    if(!localStorage.getItem("token") || localStorage.getItem("token") == undefined)
       return null;
    const programValues = this.props.programList;

    return <NavBar programs={programValues} />;
  }
}

2 个答案:

答案 0 :(得分:1)

MainLayout组件的构造函数中执行此操作。

constructor () {
  this.state = {
    isNavbarHidden: false
  };
}

在您要隐藏内容的组件的componentDidMount中

componentDidMount () {
  const currentRoute = this.props.location;
  if (currentRoute === 'YOUR_ROUTE_NAME') {
    this.setState({ isNavbarHidden: true });
  }
} // end of componentDidMount

this.props.location是一种react router方法,可以告诉您当前用户的当前路径。

现在在你的render()方法中执行类似这样的操作

render () {
    const { isNavbarHidden } = this.state;
    return (
       <div>
          {!isNavbarHidden && <NavbarComponent />}
          { /* Your rest of the code here *//}
          {this.props.children}
       </div>
    );
}

我希望这会有所帮助。干杯:)

答案 1 :(得分:0)

借助@ Adeel的帮助,我可以在我的标题容器中找出解决方案,我在代码下面添加了代码并且它有效

 constructor(props) {
    super(props);
    this.state = {
      visibility: true
    };
  }

  componentDidMount() {
         let currentRoutes = this.props.location;


if (currentRoutes.pathname === '/' || currentRoutes.pathname === '/signUp') {

    this.setState({ visibility: false });
  }

    this.props.dispatch(fetchProgramsData());
    this.props.dispatch(fetchCompany());
  }
  componentWillReceiveProps(nextProps){
 let currentRoutes = nextProps.location;
   if (currentRoutes.pathname === '/' || currentRoutes.pathname === '/signUp') {

    this.setState({ visibility: false });
  }
  else
        this.setState({ visibility: true });

  }