2017-04-27 3 views
1

먼저 내 코드입니다 리디렉션 유지 :반응 라우터 V4 인증 토큰 모두 여기의/

Routes.js :

import React from 'react'; 
import PropTypes from 'prop-types'; 
import { Redirect, Route } from 'react-router-dom'; 
import { PUBLIC_ROUTE, LOGIN_ROUTE } from './utils/constants'; 

const routes = ({ component: Component, ...rest }) => { 
    let { requireAuth, isAuthenticated } = rest; 

    if (!requireAuth) { 
     requireAuth = false; 
    } 

    // If user authenticated 
    if (isAuthenticated) { 
     // If page need auth 
     if (requireAuth === true) { 
      return (
       <Route {...rest} render={props => <Component {...props} />} /> 
      ); 
     } else if (requireAuth === 'partial') { // If the page is doesn't require auth but can't be access if auth true 
      return <Redirect to={PUBLIC_ROUTE} />; 
     } 

     // If page doesn't need auth 
     return <Route {...rest} render={props => <Component {...props} />} />; 
    } 

    // If user not authenticated // 

    // page doesn't require Auth 
    if (requireAuth === false || requireAuth === 'partial') { 
     return <Route {...rest} render={props => <Component {...props} />} />; 
    } 
    // If page require Auth redirect user to login routes 
    return (
     <Route 
      {...rest} 
      render={props => (
       <Redirect 
        to={{ 
         pathname: `${LOGIN_ROUTE}`, 
         state: { from: props.location }, 
        }} 
       /> 
      )} 
     /> 
    ); 
}; 

routes.propTypes = { 
    component: React.PropTypes.oneOfType([ 
     React.PropTypes.element, 
     React.PropTypes.func, 
    ]), 
}; 

export default routes; 

App.js :

const history = createHistory(); 

const mapStateToProps = state => { 
    const { auth, global } = state; 
    const { authenticated, user } = auth; 
    const { loading } = global; 

    return { authenticated, user, loading }; 
}; 

const reduxConnector = connect(mapStateToProps, { ping }); 

class App extends Component { 
    state = { 
     isAuthenticated: false, 
    }; 
    static propTypes = { 
     authenticated: PropTypes.bool.isRequired, 
    }; 

    componentWillReceiveProps(nextProps) { 
     this.setState({ isAuthenticated: nextProps.authenticated }); 
    } 

    render() { 
     const { authenticated, user, loading } = this.props; 
     const { isAuthenticated } = this.state; 

     if (loading) { 
      return (
       <div style={style.center}> 
        <MDSpinner /> 
       </div> 
      ); 
     } 

     return (
      <ConnectedRouter history={history}> 
       <div> 
        <NotificationsSystem theme={theme} /> 
        <Header isAuthenticated={isAuthenticated} user={user} /> 
        <NavMobile /> 
        <SideMenu /> 
        <Nav /> 

        <Switch> 
         <Routes 
          requireAuth={false} 
          isAuthenticated={isAuthenticated} 
          exact 
          path="/" 
          component={Welcome} 
         /> 

         <Routes 
          requireAuth={true} 
          isAuthenticated={isAuthenticated} 
          path="/point" 
          component={Point} 
         /> 

         <Routes 
          requireAuth="partial" 
          isAuthenticated={isAuthenticated} 
          path="/login" 
          component={Login} 
         /> 

         <Routes render={() => <h3>No Match</h3>} /> 
        </Switch> 
        <Footer /> 

       </div> 
      </ConnectedRouter> 
     ); 
    } 
} 

export default reduxConnector(App); 

을 Login.js :

import React from 'react'; 
import PropTypes from 'prop-types'; 
import { withRouter, Link, Redirect } from 'react-router-dom'; 
import { Field, reduxForm } from 'redux-form'; 
import { connect } from 'react-redux'; 
import cookie from 'react-cookie'; 

import { Headline, Section, renderField } from 'components'; 
import { ping } from 'redux/modules/auth'; 

function mapStateToProps(state) { 
    const { authenticated } = state.auth; 

    return { authenticated }; 
} 

const reduxConnector = connect(mapStateToProps, { ping }); 
const token = cookie.load('_t'); 

class Login extends React.Component { 
    static defaultProps = { 
     loggingIn: false, 
     authenticated: false, 
    }; 

    componentDidMount(){ 
     if(cookie.load('_t')){ 
      this.props.ping(); 
     } 
    } 

    render() { 
     const { handleSubmit } = this.props; 

     const { from } = this.props.location.state || { 
      from: { pathname: '/' }, 
     }; 


     if (this.props.authenticated) { 
      return <Redirect to={from} />; 
     } 

     return <div> 
       <Headline title="Login" /> 
      </div>; 
    } 
} 

export default withRouter(reduxConnector(reduxFormDecorator(Login))); 

여기에 문제가 있습니다 :

이미 내 앱에 로그인하고 있습니다. 그리고 /point (액세스 권한이 필요합니다.)으로 이동하려면 토큰 (this.props.ping())을 확인한 후 에서 /login으로 앱을 방문하십시오. 1. 토큰이 유효하면 다시 point 페이지로 리디렉션됩니다. 2. 토큰이 유효하지 않으면 페이지가 login 페이지로 리디렉션됩니다.

문제 :

  1. 후 검사 및 토큰은 유효 앱이 항상 /로 리디렉션. console.logconst {from}의 결과는 {pathname: "/point", search: "", hash: "", state: undefined, key: undefined}입니다. 이전 페이지로 돌아 가지 않습니다 (이 경우 /point 페이지).

  2. '/'에 액세스하면 ping으로 전화를 걸어 로그인 할 수 없습니다. 사용자의 성명을 보여주는 헤더가 있기 때문에 필요합니다. 그래서 나는 국가를 줄이자.

어떤 해결책이 있습니까?

답변

0

먼저 구성 요소를 마운트 한 후에 Redirect이 한 번 작동한다는 것을 알아야합니다. 다시 렌더링 할 때 중계 할 수 없습니다. API 방법 대신 history.push()을 사용할 수 있습니다.

둘째로, 나는 당신을 제대로 이해했다고 확신하지 못하지만, redux 가게에 데이터를 설정하기 위해 어딘가로 리디렉션하고 싶습니다. (어디서 찾을 수 없습니까?) 그것이 사실이라면, 그것은 나쁜 습관입니다. 로그인 후 전용 작업 내에서이 작업을 수행 할 수 있으며이 논리를 구성 요소와 관련시킬 필요가없는 경우 리디렉션이 필요하지 않습니다.

+0

나는 당신 생각을 가지고 있다고 생각합니다. 그것을 구현하려고합니다. – ssuhat

관련 문제