看看 react-router 示例 auth-with-shared-root:https ://github.com/rackt/react-router/tree/master/examples/auth-with-shared-root
他们基本上做的是检查去哪里的路线的输入。查看文件config/routes.js
第 36、51 和 89 行:
{ onEnter: redirectToLogin,
childRoutes: [
// Protected nested routes for the dashboard
{ path: '/page2',
getComponent: (location, cb) => {
require.ensure([], (require) => {
cb(null, require('../components/PageTwo'))
})
}
}
// other protected routes...
]
}
/page2
当路由进入或推送到该路由时,该路由将调用函数redirectToLogin 。如果用户通过了身份验证,该函数可以检查auth.loggedIn()
function redirectToLogin(nextState, replace) {
if (!auth.loggedIn()) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
})
}
}
如果用户未登录,该函数将替换到 的路由/login
,用户可以在其中进行身份验证。