2017-08-18 5 views
0

私はホームルート '/'を持っています。ユーザがそのルートに行くたびに、彼が認証されているか、/ 'login'ルート彼が認証されていない場合。彼のページにユーザーを送るために、私はサーバーにリクエストを行い、自分のIDを取得し、サーバーから取得したIDに基づいてルートにリダイレクトします。しかし、私は、ホームコンポーネントでそのロジックを正しく実装する方法についてちょっと混乱しています。 ajaxリクエストの結果に基づいてリダイレクトコンポーネントをレンダリングする最善の方法は何でしょうか?ajaxリクエストに基づいてリダイレクトコンポーネントをレンダリングする

あなたがこれを行うことができます
class Home extends React.Component { 

    async componentDidMount() { 
     const response = await Api.getUserId(); 
     const id = response.data._id; 
    } 

    render() { 
     if(this.props.userStatus.authenticated) { 
      return <Redirect to={{ 
       pathname: `/${id}`, 
       state: { from: this.props.location } 
      }}/> 
     } 
     return <Redirect to={{ 
      pathname: '/login', 
      state: { from: this.props.location } 
     }}/> 
    } 
} 

export default connectComponent(['userStatus'], Home); 

答えて

2

: はPrivateRouteと呼ばれる新しいコンポーネントを作成します。

import React from 'react' 
import { Redirect, withRouter, Route } from 'react-router-dom' 
import { isLogin } from '../actions/actions_rents' 
import { connect } from 'react-redux' 

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

を、コンポーネントが小道具として、あなたはあなたのルートを持っていますApp.jsかで、あなたはPrivateRouteを呼び出し、パスをこの場合、ホーム: https://reacttraining.com/react-router/web/example/auth-workflow

0:また

<Switch> 
    <Route path="/login" component={Login}/> 
    <PrivateRoute path="/" component={IndexRents} /> 
</Switch> 

、私はあなたがこの例を参照してくださいお勧めします

+0

ありがとうございますが、それは私が問題があるわけではありません。ホームコンポーネントのアイデアは、認証されたユーザーを、サーバーから取得するIDによってそれぞれのページにリダイレクトすることです。私は何が起こりたいのですか?ユーザーが '/' =>彼が認証されている場合、私は自分のIDをサーバーから(トークンを提供することによって)取り出し、個人ページにリダイレクトします。私が混乱しているのは、「取得したIDを基にしてリダイレクトしてから、非同期ロジックを取得する」という実装方法です。ユーザーをリダイレクトするルートは、サーバーから取得した結果に基づいています。 – Umbrella

0
fetch('//offline-news-api.herokuapp.com/stories') 
.then(function (response) { 
    console.log(response); 
    const login = response.ok; 
    class Entry extends React.Component { 
     constructor(props) { 
      super(props); 
     } 
     render() { 
      return (
       <Router> 
        <Switch> 
         <Route exact path="/login" component={Login}/> 
         <Route path="/" render={() => (
          login ? (
           <Common/> 
         ) : (
          <Redirect to="/login"/> 
         ) 
         )}/> 
        </Switch> 
       </Router> 
      ); 
     } 
    } 

    ReactDOM.render(<Entry/>, document.getElementById('root')); 

}) 
.then(function (stories) { 
}); 
+0

非同期の後にクラスを定義して結果を得ることができます。 –

関連する問題