繁体   English   中英

在react-router 2中以编程方式重定向到页面

[英]redirect to a page programmatically in react-router 2

我正在使用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>

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')
    }
}

成功登录后,我想从登录 component重定向到仪表板 component

要重定向,您可以使用上下文中的router对象。 您必须在组件(进行重定向的组件)中声明上下文类型。 有关上下文链接的更多信息

ES6 / 7语法:

static contextTypes = {
  router: React.PropTypes.object.isRequired
}

现在,您可以访问路由器对象,并且可以进行重定向:

this.context.router.push('/dashboard');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM