2016-03-15 14 views
5

react-router-2を使用しています。ログインに成功した後、または何らかのアクションが実行された後、プログラムでページにリダイレクトしたい。反応ルータのプログラムでページにリダイレクトする2

マイルート・ファイルには、私が後ログインcomponentからダッシュボードcomponentにリダイレクトしたい、この(routes.js)フック

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

フォーカス取得時

<Route path="/" component={App}> 
     <IndexRoute component={Home}/> 
     <Route path="/login" component={Login} onEnter={redirectToDashboard}/> 
     <Route path="dashboard" component={Dashboard} onEnter={redirectToLogin}/> 
    </Route> 

のようなものですログインに成功しました。

答えて

5

リダイレクトするには、コンテキストからrouterオブジェクトを使用できます。コンポーネント(リダイレクションを行うコンポーネント)でコンテキストタイプを宣言する必要があります。コンテキストの詳細link

ES6/7構文:

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

は今、あなたは、ルータのオブジェクトへのアクセス権を持っているとあなたが作ることができますリダイレクト:

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