我在我的项目中使用react-router-dom
。我有一个值叫做auth
,我从localStorage
得到它当auth
没有值时,我想进入登录页面。我如何重定向?
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>
);
}
试试代码,让我知道它是如何为你工作的。
<Router>
<Switch>
<Route exact path='/' component={Login} />
<Route exact path='/admin/'>
{userData?<Redirect to="admin/dashboard" />:<Redirect to="/"/>}
</Route>
</Switch>
</Router>
你需要一个路由器保护,使用这个包你可以创建简单的路由器保护。
例如:
import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import { GuardProvider, GuardedRoute } from 'react-router-guards';
import { About, Home, Loading, Login, NotFound } from 'pages';
import { getIsLoggedIn } from 'utils';
const requireLogin = (to, from, next) => {
if (to.meta.auth) {
if (getIsLoggedIn()) {
next();
}
next.redirect('/login');
} else {
next();
}
};
const App = () => (
<BrowserRouter>
<GuardProvider guards={[requireLogin]} loading={Loading} error={NotFound}>
<Switch>
<GuardedRoute path="/login" exact component={Login} />
<GuardedRoute path="/" exact component={Home} meta={{ auth: true }} />
<GuardedRoute path="/about" exact component={About} meta={{ auth: true }} />
<GuardedRoute path="*" component={NotFound} />
</Switch>
</GuardProvider>
</BrowserRouter>
);