我在我的应用程序中使用了 ReactJS
和 react-router
。我需要做下一件事:当用户打开页面时 - 检查他是否登录,如果是,则重定向到 /auth
页面。我在做下一件事:
componentWillMount: function() {
if (sessionStorage["auth"] == null) {
this.transitionTo("/auth");
}
},
在浏览器 url 中,它确实会重定向到 /auth
,呈现 /auth
页面,然后用当前组件覆盖它。所以这里的问题是:如何取消当前组件的渲染,或者如何以其他方式进行重定向?谢谢。
最佳答案
看看 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
的路由,用户可以在此处验证自己。
关于javascript - ReactJS 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28040912/