首页 > 解决方案 > 单击 /profile 后,我登陆路径 /login。在 /profile 上再次完成登录后如何自动登陆?

问题描述

我正在使用 reactrouter。我没有登录我点击 /profile 链接。然后我被转发到 /login (工作正常)。成功登录后,我登陆家而不是 /profile

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

render() {
    const loggedIn = this.props.isLoggedIn;

    return(
        <Switch>

        <Route exact path="/" component={ UserPanel } />
        <Route exact path="/confirm" component={ EmailConfirmation } />

        {/* <Route exact path="/admin" component={ AdminPanel } /> */}
        <Route exact path="/login" render={(props) => ( loggedIn
            ? <Redirect to='/' />
            : <Login/>
          )} />

          <PrivateRoute path='/admin' component={AdminPanel} authed = {this.props.admin}/>
        <PrivateRoute path='/createevent' component={CreateEvent} authed = {loggedIn}/>
        <PrivateRoute path='/profile' component={Profile} authed = {loggedIn}/>
        </Switch>

    )
}

标签: reactjsreact-router

解决方案


目前,您似乎已经Redirect在私有路由上设置了一个状态:

<Redirect to={{
  pathname: '/login',
  state: { from: props.location }
}}
/>

现在,您可以在 Login 组件上利用此状态将用户重定向回他的来源。从docs借用 Login 组件:

function LoginPage() {
  let history = useHistory();
  let location = useLocation();

  let { from } = location.state || { from: { pathname: "/" } };
  let login = () => {
    fakeAuth.authenticate(() => {
      history.replace(from);
    });
  };

  return (
    <div>
      <p>You must log in to view the page at {from.pathname}</p>
      <button onClick={login}>Log in</button>
    </div>
  );
}

来自 location 的状态被提取到一个变量中,from或者如果它不存在(用户根据自己的意愿来到路线,输入 URL 或单击按钮)将其/默认设置为。

稍后在成功验证后,用户被重定向到from.


推荐阅读