登录成功后重定向到先前的路由。

6

我在尝试理解最佳实践和处理重定向的位置时遇到了很大的困难。

我找到了一个创建 ProtectedRoute 组件的示例,其设置如下:

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

并像这样使用

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

我使用redux-thunk确保我的actions可以使用异步fetch请求,并且设置类似于以下内容:

Actions

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)));
  };
};

Reducers

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

在哪里以及如何处理重定向到登录页面之前的位置,并且如何确保这仅在登录成功的情况下发生?

1个回答

5
你的受保护路由很好。当用户未经身份验证时,这将使你路由到登录路由。
在你的高级 react-router `` 中,你需要嵌套: `` 以创建一个 Login 路由。
然后在你的 `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>
    )
  }
}

这个组件将会调用一个登录的 action-creator 函数 (该函数又会去调用你的 API)。如果成功,它将改变 redux 状态。Login 组件将被重新渲染,若 auth.redirectToReferrer 为真,则会重定向。请参阅文档:https://reacttraining.com/react-router/web/example/auth-workflow

这太棒了,而且很有意义!我不得不在我的 reducer 中的初始状态中添加 redirectToReferrer 并成功在 LOGGIN_SUCCESS 动作处理程序中更改它。但除此之外,一切都很好! - Jordan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接