我有一个具有多个路由和子路由的路由器配置。如果用户未经授权,我需要将其重定向到除一个以外的所有页面的授权页面。 我的基本配置是这样的
</Route>
<Route path = "auth" handler = {Auth}/>
<Route handler = {App}>
<Route handler = {Container}>
<Route path = "page1" handler = {Page1}/>
<Route path = "page2" handler = {Page2}/>
<Route path = "page3" handler = {Page3}/>
</Route>
</Route>
</Route>
我需要将用户重定向到/ auth,如果他是未经授权的,但我需要让用户访问page2
答案 0 :(得分:6)
对您的路线采用auth-flow解决方案:
在您的应用程序的某个位置,无论是redux
状态还是全局变量或API单例,您都会有一个值,指示用户是否已获得授权,这是auth
所指的内容在这个例子中。为需要身份验证的路由定义onEnter
处理程序:
function requireAuth(nextState, replace) {
if (!auth.loggedIn()) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
})
}
}
然后在需要检查的路线上使用
<Route>
<Route path = "auth" handler = {Auth}/>
<Route handler = {App}>
<Route handler = {Container}>
<Route path = "page1" handler = {Page1}/>
<Route path = "page2" handler = {Page2}/>
<Route path = "page3" handler = {Page3} onEnter = { requireAuth } />
</Route>
</Route>
</Route>