如果经过身份验证的NextJS Redux重定向

时间:2020-01-06 20:26:45

标签: reactjs redux next.js

我正在与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);

它可以正常工作并重定向用户,但是要等到状态出现才能重定向用户。

有没有一种方法可以在我已经拥有状态或防止状态发生之前不呈现页面?

1 个答案:

答案 0 :(得分: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是一种在加载完成后变为false的状态。