如何在React路由器的登录页面中隐藏导航栏

我想在登录页面中隐藏导航栏。

我确实做到了,但是在其他页面上看不到导航栏。

该代码是My App.jsx文件的一部分。

我在App的状态下创造历史。当此路径名是“ /”或“ / login”时,我隐藏了导航栏。

有用!

但是然后我输入了ID和密码,然后单击登录按钮,获得“成功”结果,并导航到“ / main”。

现在我在主组件中也看不到导航栏。

我怎样才能做到这一点?

对不起,我的英文简短。 如果您不明白我的问题,可以发表评论。

constructor(props) {

super(props);

this.state = {

isAlertOpen: false,

history: createBrowserHistory(),

};

this.toggleAlert = this.toggleAlert.bind(this);

}

<BrowserRouter>

<div className="App">

{this.state.history.location.pathname === '/' || this.state.history.location.pathname === '/login' ? null

: <Header toggleAlert={this.toggleAlert} />}

<div className="container">

{this.state.history.location.pathname === '/' || this.state.history.location.pathname === '/login' ? null

: <Navbar />}

<Route exact path="/" render={() => <Redirect to="/login" />} />

<Route path="/login" component={Login} />

<Route path="/main" component={Main} />

<Route path="/user" component={User} />

<Route path="/hw-setting" component={Setting} />

<Route path="/hw-detail/:id" component={HwDetail} />

<Route path="/gas-detail/:id" component={GasDetail} />

{this.state.isAlertOpen ? <Alert /> : null}

</div>

</div>

</BrowserRouter>

login(event) {

event.preventDefault();

userService.login(this.state.id, this.state.password).subscribe(res => {

if (res.result === 'success') {

global.token = res.token;

this.props.history.push('/main');

} else {

alert(`[ERROR CODE : ${res.statusCode}] ${res.msg}`);

}

});

回答:

您可以采用Routes不同的结构,以使Login组件没有HeaderLike

<BrowserRouter>

<Switch>

<div className="App">

<Route exact path="/(login)" component={LoginContainer}/>

<Route component={DefaultContainer}/>

</div>

</Switch>

</BrowserRouter>

const LoginContainer = () => (

<div className="container">

<Route exact path="/" render={() => <Redirect to="/login" />} />

<Route path="/login" component={Login} />

</div>

)

const DefaultContainer = () => (

<div>

<Header toggleAlert={this.toggleAlert} />

<div className="container">

<Navbar />

<Route path="/main" component={Main} />

<Route path="/user" component={User} />

<Route path="/hw-setting" component={Setting} />

<Route path="/hw-detail/:id" component={HwDetail} />

<Route path="/gas-detail/:id" component={GasDetail} />

{this.state.isAlertOpen ? <Alert /> : null}

</div>

</div>

)

以上是 如何在React路由器的登录页面中隐藏导航栏 的全部内容, 来源链接: utcz.com/qa/399329.html

回到顶部