reactjs - 如何重定向到登录页面?
问题描述
我react-router-dom
在我的项目中使用。我有一个名为auth
And I get it from localStorage
And I want to go to the login page when auth
has no value ..如何重定向?
return (
this.state.auth ?
<div className="wrapper" >
<div id='content' className={this.state.isSidebarActive ? "content" : "content-active"}>
<Switch>
<Route exact path='/main' >
<Redirect to='/main/customers/real' />
</Route>
<Route path="/main/access/deny"><NoAccess isSidebarActive={this.state.isSidebarActive} /></Route>
....
</Switch>
</div>
</div>
:
<Switch>
<Route exact path='/' >
<Redirect to='/Login' />
</Route>
</Switch>
);
解决方案
不知道为什么要分开 switch router 语句,但最好将它们放在一起。
<Switch>
<Route exact path='/main' > <Redirect to='/main/customers/real' /> </Route>
<Route path="/main/access/deny"><NoAccess isSidebarActive={this.state.isSidebarActive} /></Route>
<Route exact path='/' > <Redirect to='/Login' /> </Route>
</Switch>
我也不知道你为什么要重定向这么多次。在进入永恒循环之前,您可能需要注意这一点。
更新
我喜欢对正在做的事情非常明确,所以我将三元语句切换到下面。
if(this.state.auth != null)
{
return(
<div className="wrapper">
<div id='content' className={this.state.isSidebarActive ? "content" : "content-active"}>
<Switch>
<Route exact path='/main' >
<Redirect to='/main/customers/real' />
</Route>
<Route path="/main/access/deny"><NoAccess isSidebarActive={this.state.isSidebarActive} /></Route>
....
</Switch>
</div>
</div>
);
}
else
{
return(
<Switch>
<Redirect to='/Login' />
</Switch>
);
}
试试代码,让我知道它是如何为你工作的。
推荐阅读
- javascript - ClickMarker 在 XY Amcharts 中不起作用
- java - 由于缺少 ReactiveWebServerFactory bean,无法启动 ReactiveWebApplicationContext
- reporting-services - SSRS饼图分割一个切片
- excel - 将 Excel 连接到 Power BI 数据模型
- java - TWS Java API 编辑AddJobStreamInstanceWithVariableSubstitution
- autohotkey - AHK 脚本在每次连续按下时发送不同的按钮
- ajax - 使用ajax从json读取和显示值
- angular - 如何覆盖 ngrx 商店中的某些操作?
- sql - sql group 通过忽略大小写和后缀或最后一个字母
- r - 使用组变量创建新列