2015-12-06 31 views
12

反応ルータ(v1.1.0)の最新バージョンで使用できるリダイレクトメカニズムを理解するのを手伝ってください。 ユーザーのログインの成功または失敗に応じて、urlにリダイレクトします。 私は以下を実行しようとしました 最初に履歴を使用して作成しました。反応ルータ - ログイン後のリダイレクト

let history = createBrowserHistory(); 

はその後何も起こりません

​​

を使用して状態をプッシュしようとしました。移行を行う正しい方法を教えてください。ドキュメントから、私はtransitionTo() APIが最新バージョンに存在しないことを理解しました。 簡単な実例を指すことができればそれは素晴らしいことでしょう。

ありがとうございます。

+1

[反応ルータでログインした後の自動リダイレクト]の可能な複製(0120-13-03)。 –

答えて

17

ルートに入力して離れるときにトリガーされる「フック」を登録することができます。 onEnter and onLeave hooksのドキュメントをご覧ください。 。

ありexample of requiring authがルート上にもあり、ユーザーがログインしていない場合は別のパスにリダイレクト

はここapp.js内のauth例を必要とするから取られたスニペットです:

function requireAuth(nextState, replaceState) { 
    if (!auth.loggedIn()) 
    replaceState({ nextPathname: nextState.location.pathname }, '/login') 
} 

// And from the route configuration, use the requireAuth function in onEnter... 
<Router history={history}> 
    <Route path="/" component={App}> 
    <Route path="login" component={Login} /> 
    <Route path="logout" component={Logout} /> 
    <Route path="about" component={About} /> 
    <Route path="dashboard" component={Dashboard} onEnter={requireAuth} /> 
    </Route> 
</Router> 

nextStatereplaceState引数はrackt/historyのオブジェクトで、onEnterに渡すメソッドに注入されます。

+0

ありがとう。さらに1つのクエリ。反応ルータのはビューの角度に相当しますか? –

9

@terranmoccasinの答えは正しいです。しかし、一般的な必要性は非常に少数の例に対処しています。

たとえば、複数のルート(dashboard1、dashboard2、...)を保護する必要があるとします。ログイン後、どのように元のページにリダイレクトするのですか?つまり、{nextPathname: nextState.location.pathname}で何をしていますか?ここで

は、私が./containers/LoginContainer.jsに何をすべきかです:

import { push } from 'react-router-redux'; 
const mapStateToProps = (state) => ({ 
    nextPathname: state.routing.locationBeforeTransitions.state.nextPathname, 
}); 
const mapDispatchToProps = (dispatch) => ({ 
    changeLocationOnSignIn: (nextPathname) => { 
    dispatch(push(nextPathname)); 
    }, 
}); 

./components/Login.js

componentWillReceiveProps(nextProps) { 
    // user signed in or signed up, assuming redux. you may use this elsewhere. 
    if (nextProps.user.status === 'authenticated' && nextProps.user.user && 
    !nextProps.user.error) { 
     this.props.changeLocationOnSignIn(this.props.nextPathname); 
    } 

で反応ルータ2.4.0(2016年4月)をHOCを作成するwithRouterを導入しました。ただし、JSクラスではなくReact.createClassをラップします。私はそれをredux形式などで動作させることができませんでした。私は、上記のコードは理解しやすいと考えています。

+0

@justabuzzを参照すると、私はReduxを使用していたことを言及する必要があります。リダイレクトをReduxで記録したかったのです。そうでなければ、push()はOKです。 – JohnSz

0

@ JohnSzが私にもwithRouterの使用に問題があると言います。ここでの指示通りに代わり、私はそれをやった: 基本的にhttps://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.0.0.md#programmatic-navigation

const RouteComponent = React.createClass({ 
    contextTypes: { 
    router: React.PropTypes.object.isRequired 
    }, 
    someHandler() { 
    this.context.router.push(...) 
    } 
}) 

  1. (this.context.router.pushを使用contextType
  2. を定義します...)

乾杯。

20

このスレッドを更新するには、かなりの時間を費やしていましたので、このスレッドを更新したいと考えました。 React Router 2.0.xでは、replaceStateは置き換えられなくなりました。詳細はこちらをご覧ください:https://github.com/ReactTraining/react-router/blob/v2.0.0/upgrade-guides/v2.0.0.md#link-to-onenter-and-isactive-use-location-descriptors

これを行うための正しい方法はこのようなものになるだろう:

function requireAuth(nextState, replace) { 
    if (!userExists()) { 
    replace({ 
     pathname: '/signin', 
     state: { nextPathname: nextState.location.pathname } 
    }) 
    } 
} 

export const renderRoutes =() => (
    <Router history={browserHistory}> 
     <Route path="protectedRoute" component={Protected} onEnter={requireAuth} /> 
     <Route path="signin" component={SignIn} /> 
    </Route> 
    </Router> 
); 

次に、サインインコンポーネントで、あなたはこのように成功記号の後にリダイレクトすることができます

signInFunction({params}, (err, res) => { 
    // Now in the sign in callback 
    if (err) 
    alert("Please try again") 
    else { 
    const location = this.props.location 
    if (location.state && location.state.nextPathname) { 
     browserHistory.push(location.state.nextPathname) 
    } else { 
     browserHistory.push('/') 
    } 
    } 
}) 
+0

ありがとうございます。これは私のために働いた唯一の答えでした。 – dannymac

+0

これは受け入れられたよりも良い答えです。 +1 signin関数です。 – technophyle

+0

これらのReactリポジトリは移行し続ける! https://github.com/ReactTraining/react-router/blob/v2.0.0/upgrade-guides/v2.0.0.md#link-to-onenter-and-isactive-use-location-descriptors – ptim

1

は、ルータV4.2

0に反応します私は従っていました

.then(response => response.json()) 
     .then(data => { 
      if(data.status == 200){ 
       this.props.history.push("/"); 
       console.log('Successfully Login'); 
      } 
     }) 

私は & リアクト - ルータ - 4.2

から16.2に反応し、私はこの this.props.history.push("/");

で私の作業コードを解を得るを使用していますこの文書redirect-on-login-and-logout

関連する問題