2017-11-08 9 views
1

React Routerの例に続いて、Graphactを使用して単純な認証フローを作成することに問題があり、Reactと新規に対処しました。React Router認証フローを設定するにはどうしたらいいですか?

私は/を私のログイン画面にしたいと思います。ユーザがログアウトしている場合にのみ表示されます。そうでない場合は、/dashboardにリダイレクトする必要があります(別の方法ではアクセスできない)。ここでは、認証後に無限ループを生成し、私が持っているものです。

class App extends Component { 
    constructor(props) { 
     super(props); 

     this.state = { 
      authenticated: false 
     } 
    } 

    renderButtons() { 
     if (this.state.authenticated) { 
      return (
       <a>Logout</a> 
      ) 
     } 
     return null; 
    } 

    componentWillReceiveProps({ data }) { 
     if (this.props.data.loading && !data.loading) { 
      if (data.loggedInUser.id && !this.state.authenticated) { 
       this.setState({authenticated: true}); 
      } else if (this.state.authenticated) { 
       this.setState({authenticated: false}); 
      } 
     } 
    } 

    render() { 
     return (
      <div className="container"> 
       <nav> 
        {this.renderButtons()} 
       </nav> 
       <GatingRoute path="/" component={LoginPage} isAuthenticated={this.state.authenticated} newPath="/dashboard" /> 
       <PrivateRoute path="/dashboard" component={Dashboard} isAuthenticated={this.state.authenticated} /> 
      </div> 
     ); 
    } 
}; 

const PrivateRoute = ({ component: Component, isAuthenticated, ...rest}) => (
    <Route 
     {...rest} 
     render={props => (
     isAuthenticated 
     ? (
      <Component {...props} /> 
     ) 
     : (<Redirect to={{ pathname: '/', state: { from: props.location } }} />) 
    )} 
    /> 
    ); 

const GatingRoute = ({ component: Component, isAuthenticated, newPath, ...rest}) => (
    <Route 
     {...rest} 
     render={props => (
     isAuthenticated 
     ? (
      (<Redirect to={{ pathname: newPath, state: { from: props.location } }} />) 
     ) 
     : 
     <Component {...props} /> 
    )} 
    /> 
    ); 

export default graphql(query, { options: {fetchPolicy: 'network-only'}})(withRouter(App)); 

答えて

1

のではなく、あなたが今の道を働いて...あなたはあなたのルートを持っているあなたの親コンポーネントで

次のようにします
<BrowserRouter> 
    <Route path=“/“ exact   render={ (props) => 
props.user.loggedIn ? <Dashboard /> : <LoginForm /> 
}/> 
</BrowserRouter> 

これは、ルータをレンダリングするコンポーネントがユーザステータスを認識していることを前提としています。

モバイルでのフォーマットが貧弱であることを申し訳ありません。

+1

親オブジェクトからルートへの認証プロップの取得方法がわからないため、これは実際には私にとってはうまくいきませんでした。ただし、行った動的JSX、このアプローチに影響を与えた作品: 'renderRoute(){ IF(this.state.authenticated){ リターン( <ルート正確なパス= "/" コンポーネント= {ダッシュボード} /> ) }他{ リターン( <= "/" コンポーネント= {LoginFormルートの正確なパス} /> ) }} ' – ed94133

+0

ロング私は満足しているあなたのために働く方法を発見したとして。 –

関連する問題