【问题标题】:redirect to a page programmatically in react-router 2在 react-router 2 中以编程方式重定向到页面
【发布时间】:2016-07-01 13:02:59
【问题描述】:

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

我想在成功登录后从 Login component 重定向到 Dashboard component

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

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

    ES6/7 语法:

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

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

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

    【讨论】:

    • 不推荐使用 this.context
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 2017-10-31
    • 2017-09-18
    • 2016-03-07
    • 2018-11-27
    • 2021-11-10
    • 1970-01-01
    相关资源
    最近更新 更多