Wit*_*ult 5 javascript reactjs react-router
我正在使用react-router-2.我想在成功登录后或执行某些操作后以编程方式重定向到页面.
我的路线文件是这样的(routes.js)
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="/login" component={Login} onEnter={redirectToDashboard}/>
<Route path="dashboard" component={Dashboard} onEnter={redirectToLogin}/>
</Route>
Run Code Online (Sandbox Code Playgroud)
onEnter钩子
function redirectToLogin(nextState, replace) {
// Perform some authentication check
if (!loggedIn) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
});
}
}
function redirectToDashboard(nextState, replace) {
// Perform some check if already authenticated
if (loggedIn) {
replace('/dashboard')
}
}
Run Code Online (Sandbox Code Playgroud)
登录成功后,我想从Login重定向到Dashboard .component component
要重定向,您可以使用router上下文中的对象.您必须在组件中声明上下文类型(从中进行重定向的组件).更多关于上下文链接
ES6/7语法:
static contextTypes = {
router: React.PropTypes.object.isRequired
}
Run Code Online (Sandbox Code Playgroud)
现在您可以访问路由器对象,并可以进行重定向:
this.context.router.push('/dashboard');
Run Code Online (Sandbox Code Playgroud)