在react-router 2中以编程方式重定向到页面 [英] redirect to a page programmatically in react-router 2

查看:113
本文介绍了在react-router 2中以编程方式重定向到页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 react-router-2 。我想在成功登录后或执行某些操作后以编程方式重定向到页面。

I am using react-router-2. I want to redirect to a page programmatically after successful login or after some action performed.

我的路径文件是这样的( routes.js

My route file is like this(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')
    }
}

我想要成功登录后,从登录 组件重定向到信息中心 组件

I want to redirect to Dashboard component from Login component after successful login.

推荐答案

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

To redirect you can use router object from context. You have to declare context types in your component (component from which you make redirection). More about context link

ES6 / 7语法:

ES6/7 syntax:

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

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

Now you have access to router object and you can make redirection:

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

这篇关于在react-router 2中以编程方式重定向到页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆