2015-10-01 7 views
52

コンポーネントの取り付け前に認可チェックのベストプラクティスは何ですか?リアクタ認可

私はここで反応し、ルータを1.1

を使用する私のルートはここ

React.render((
    <Router history={History.createHistory()}> 
    <Route path="/" component={Dashboard}></Route> 
    <Route path="/login" component={LoginForm}></Route> 
    </Router> 
), document.body); 

ある私のダッシュボードコンポーネントです:

var Dashboard = React.createClass({ 
    componentWillMount: function() { 
    // I want to check authorization here 
    // If the user is not authorized they should be redirected to the login page. 
    // What is the right way to perform this check? 
    }, 

    render: function() { 
    return (
     <h1>Welcome</h1> 
    ); 
    } 
}); 
+3

https://github.com/rackt/react-router/tree/master/examples/auth-flowを行うことができますか?クッキーから?サーバーコールからですか?私はそれが 'componentWillMount'ではなく' Route'の 'onEnter'で一般的に行われていると思います。 '<経路パス='/'コンポーネント= {ダッシュボード} onEnter = {function(nextState、transition){if(!USER_IS_AUTHED){transition.to(' login '); }})} ' – Dylan

答えて

53
ため

更新ソリューションは、ルータv4の に反応

<Route 
    path="/some-path" 
    render={() => !isAuthenticated ? 
    <Login/> : 
    <Redirect to="/some-path" /> 
}/> 

はv3の

使用「フォーカス取得時」イベントまでのルータを反応させ、ユーザが許可されている場合、コールバックチェックで:反応-ルータ4で

<Route path="/" component={App} onEnter={someAuthCheck}> 

const someAuthCheck = (nextState, transition) => { ... } 
+5

例とドキュメントの点では、状況は悪化しています。 「auth-flow」の例は私のためには機能しません。ハンドラの2番目のパラメータが受け入れるべき情報を見つけるのは簡単ではありません。 – backdesk

+0

onEnter(nextState、replace、callback?) "ルートを入力しようとしたときに呼び出され、次のルータの状態と*別のパスにリダイレクトする機能*を提供します。 " – backdesk

+0

あなたはドキュメントとバージョンを指すことができます私は更新を行います。 – Pawel

5

をあなたはRoute propsへのアクセス権を持っていますコンポーネントの内部にあります。ユーザーをリダイレクトするには、新しいURLを履歴にプッシュするだけです。あなたの例では、コードは次のようになります。

var Dashboard = React.createClass({ 
    componentWillMount: function() { 
    const history = this.props.history; // you'll have this available 
    // You have your user information, probably from the state 
    // We let the user in only if the role is 'admin' 
    if (user.role !== 'admin') { 
     history.push('/'); // redirects the user to '/' 
    } 
    }, 

    render: function() { 
    return (
     <h1>Welcome</h1> 
    ); 
    } 
}); 

ドキュメントでは、彼らが代わりにcomponentの、renderプロパティを使用して、another way to do itを示しました。それらはPrivateRouteを定義します。これは、すべてのルートを定義するときにコードを非常に明示的にします。

0

複数のコンポーネントで承認を適用する場合は、このようにすることができます。

<Route onEnter={requireAuth} component={Header}> 
    <Route path='dashboard' component={Dashboard} /> 
    <Route path='events' component={Events} /> 
</Route> 

単一のコンポーネントのためにあなたはどのようにあなたががチェックされている

<Route onEnter={requireAuth} component={Header}/> 

function requireAuth(nextState, replaceState) { 
    if (token || or your any condition to pass login test) 
    replaceState({ nextPathname: nextState.location.pathname }, 
    '/login') 
} 
関連する問題