2017-11-28 5 views
4

이 작업을 수행하는 가장 좋은 방법과이 리디렉션을 처리 할 위치를 이해하는 데 많은 시간을 할애하고 있습니다. 로그인 성공 후 이전 경로로 리디렉션

나는이

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

같은 설정이있는 ProtectedRoute 구성 요소를 생성하는 예제를 발견 그리고 난에 fetch 요청 비동기 사용할 수 있는지 확인하기 위해 내가 redux-thunk을 사용하여이

<ProtectedRoute path="/" component={HomePage} exact /> 

처럼 사용할 내 액션과 이것들은 다음과 같이 설정됩니다.

액션

export const loginSuccess = (user = {}) => ({ 
    type: 'LOGIN_SUCCESS', 
    user 
}); 

... 

export const login = ({ userPhone = '', userPass = '' } = {}) => { 
    return (dispatch) => { 
    dispatch(loggingIn()); 
    const request = new Request('***', { 
     method: 'post', 
     body: queryParams({ user_phone: userPhone, user_pass: userPass }), 
     headers: new Headers({ 
     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' 
     }) 
    }); 
    fetch(request) 
     .then((response) => { 
     if (!response.ok) { 
      throw Error(response.statusText); 
     } 

     dispatch(loggingIn(false)); 

     return response; 
     }) 
     .then((response) => response.json()) 
     .then((data) => dispatch(loginSuccess(data.user[0]))) 
     .catch((data) => dispatch(loginError(data))); 
    }; 
}; 

기어

export default (state = authenticationReducerDefaultState, action) => { 
    switch (action.type) { 
    ... 
    case 'LOGIN_SUCCESS': 
     return { 
     ...state, 
     authenticatedUser: action.user 
     }; 
    default: 
     return state; 
    } 
}; 

어떻게 내가 내가 로그인 페이지로 이동하기 전에 가고, 그리고 한 곳으로 리디렉션을 처리 가겠어요 어떻게 내가이 단지 성공을 어떻게 확인 할 수 있습니다 로그인 가져 오기 약속에서?

답변

3

귀하의 보호 경로가 좋습니다. 이렇게하면 사용자가 인증되지 않은 경우 사용자를 로그인 경로로 안내합니다. <Route path="/login" component={Login}/> 는 로그인 경로를 만들 : 당신이 중첩해야합니다 <router> 당신의 높은 수준의 반응 라우터에서

.

그런 다음 Login 경로 구성 요소에서 사용자가 로그인 할 수 있도록 UI를 렌더링합니다.

class Login extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     userPhone: '', 
     userPass: '' 
    } 
    } 

    handleLogin() { 
    this.props.login({ userPhone, userPass }) 
    } 

    handlePhoneChange(event) { 
    const { value } = event.currentTarget; 
    this.setState({ userPhone: value }); 
    } 

    handlePasswordChange(event) { 
    const { value } = event.currentTarget; 
    this.setState({ userPass: value }); 
    } 

    render() { 
    // this is where we get the old route - from the state of the redirect 
    const { from } = this.props.location.state || { from: { pathname: '/' } } 
    const { auth } = this.props 

    if (auth.redirectToReferrer) { 
     return (
     <Redirect to={from}/> 
    ) 
    } 

    return (
     <div> 
     <input 
      value={this.state.userPhone} 
      onChange={this.handlePhoneChange.bind(this)} 
     /> 
     <input 
      type="password" 
      value={this.state.userPass} 
      onChange={this.handlePasswordChange.bind(this)} 
     /> 
     <button onClick={this.handleLogin.bind(this)}>Log in</button> 
     </div> 
    ) 
    } 
} 

이 구성 요소는 login action-creator 함수 (API를 호출 함)를 호출합니다.

성공하면 redux 상태가 변경됩니다. 이렇게하면 Login 구성 요소가 다시 렌더링되고 auth.redirectToReferrer이 true 인 경우 리디렉션됩니다. (위의 코드 스 니펫 참조)

문서의 경우 https://reacttraining.com/react-router/web/example/auth-workflow을 참조하십시오.

+0

환상적이며 의미가 있습니다. 감속기에서 'redirectToReferrer'를 초기 상태에 추가하고 거기서 내'LOGGIN_SUCCESS' 액션 핸들러에서 변경해야했습니다. 그러나 그것 이외에 그것은 잘 작동합니다! – Jordan

관련 문제