2017-07-14 13 views
0

私はルートにナビゲートするたびに呼び出される汎用コンポーネントを持っていたいと思います。このコンポーネントの主な目的は認証です。ReactJsの認証コンポーネント

const routes = [ 
    { path: '/', component: Login, meta: { auth: false } }, 
    { path: '/dashboard', component: Dashboard, meta: { auth: true } }, 
]; 

router.beforeEach((to, from, next) => { 
    if(to.meta.auth) { 
     // run auth, then next(); 
    } else { 
     next(); 
    } 
}) 

私はReactJsでこのようになめらかを達成することができます:vue.jsがあれば、私はこの例を持って必要なものをよりよく説明するために?

答えて

1

が認証されたルートを実装する方法の例がある(あなたがこのルータのライブラリを使用しようとしていると仮定)

PrivateRouteの内部では、認証ステータスをthis.isLoggedIn()で確認し、返されたブール値に基づいて、コンポーネントまたはRedirect(ログインページなど)がレンダリングされます。

+0

trueかfalseを定義するためにajax呼び出しを行うことはできますか? – mikek

+0

もちろん、 'isLoggedin()'の中でフェッチプロミス(https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)を返し、 'PrivateRoute'の中でレスポンスをチェックすることができます: 'this.isLoggedin()。then((response)=> {// return または}' –

1

ログインロジックを含む反応コンポーネントを作成できます。このコンポーネントは、認証されたユーザーを必要とするすべてのルートをラップします。解決方法はarticleにチェックしてください。あなたの例を使用してhttps://reacttraining.com/react-router/web/example/auth-workflow

あなたはこの

import React, { Component } from 'react'; 
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom'; 

import Login from './Login'; 
import Dashboard from './Dashboard'; 

const routes = [ 
    { path: '/', component: (props) => <Login {...props} />, meta: { auth: false } }, 
    { path: '/dashboard', component: (props) => <Dashboard {...props} />, meta: { auth: true } }, 
]; 

export default class MyRouter extends Component { 

    isLoggedin() { 
    // run auth check that will return true/false 
    return true; 
    } 

    render() { 
    // if loggedin => render component, if not => redirect to the login page 
    const PrivateRoute = ({ component: RouteComponent, ...rest }) => (
     <Route 
     {...rest} 
     render={props => (
     this.isLoggedin() ? (
      <RouteComponent {...props} /> 
     ) : (
      <Redirect to={{ pathname: '/login', state: { from: props.location } }} /> 
     ) 
    )} 
     /> 
    ); 

    return (
     <BrowserRouter> 
     <Switch> 
      {routes.map((route, index) => (
      route.meta.auth ? 
       <PrivateRoute key={index} path={route.path} exact component={route.component} /> 
      : 
       <Route key={index} path={route.path} exact component={route.component} /> 
     ))} 
     </Switch> 
     </BrowserRouter> 
    ); 
    } 
} 
ようにそれを実現することができます。 react-routerのマニュアルの
関連する問題