【问题标题】:Redirect if authenticated NextJS Redux如果经过身份验证,则重定向 NextJS Redux
【发布时间】:2020-01-06 20:26:45
【问题描述】:

我正在使用 Redux 学习 NextJS,并且我创建了一个商店并设法让用户在通过身份验证后进入 Eedux 状态,但现在我不希望该用户在通过身份验证后访问登录页面。

这是我目前写的代码:

const SignInSignUp = ({ currentUser }) => {
  const StyledSignInSignUp = styled.div`
    display: flex;
    align-items: center;
    justify-content: space-between;
  `;

  const renderSignIn = () => {
    if (currentUser) {
      Router.push('/');
    } else {
      return (
        <StyledSignInSignUp>
          <SignIn />
          <SignUp />
        </StyledSignInSignUp>
      );
    }
  };

  return (
    <motion.div
      initial={{ y: 50 }}
      animate={{ y: 0 }}
      exit={{ y: 50 }}
      className="container"
    >
      {renderSignIn()}
    </motion.div>
  );
};

const mapStateToProps = ({ user }) => ({ currentUser: user.currentUser });

export default connect(mapStateToProps)(SignInSignUp);

它可以工作并重定向用户,但在重定向之前需要大约 3 秒的时间才能到达状态。

有没有办法在我已经拥有状态之前不呈现页面或防止这种情况发生?

【问题讨论】:

  • 你看到我的回答了吗?

标签: reactjs redux next.js


【解决方案1】:

你可以在你的 return 语句中有一个条件,当你加载关于用户是否登录的信息时,你只渲染一个片段:

const SignInSignUp = ({ currentUser, isUserLoading }) => {
  const StyledSignInSignUp = styled.div`
    display: flex;
    align-items: center;
    justify-content: space-between;
  `;

  const renderSignIn = () => {
    if (currentUser) {
      Router.push('/');
    } else {
      return (
        <StyledSignInSignUp>
          <SignIn />
          <SignUp />
        </StyledSignInSignUp>
      );
    }
  };

  return (
    <motion.div
      initial={{ y: 50 }}
      animate={{ y: 0 }}
      exit={{ y: 50 }}
      className="container"
    >
      {!isUserLoading ? renderSignIn() : <></>}
    </motion.div>
  );
};

const mapStateToProps = ({ user }) => ({ currentUser: user.currentUser, isUserLoading: user.isUserLoading (UPDATE THIS) });

export default connect(mapStateToProps)(SignInSignUp);

其中isUserLoading 是在您完成加载后变为假的状态。

【讨论】:

  • 是的,我看到了它,它确实有效,但我忘了把它标记为我的坏哈哈。
猜你喜欢
  • 2018-05-11
  • 2016-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-19
  • 2023-01-20
  • 2018-02-22
  • 2016-12-30
相关资源
最近更新 更多