【问题标题】:How to redirect in Next.Js (CLIENT SIDE)如何在 Next.Js 中重定向(客户端)
【发布时间】:2020-12-02 22:06:59
【问题描述】:

如果用户是否有保存在 cookie 中的令牌,我正在尝试进行重定向,这是我的代码:

const Secret = () => {
  const router = useRouter();
  const [token] = useState({
    token: cookies.get("token") || null,
  });
  if (token.token == null || token.token.hasOwnProperty("error")) {
    router.push("/login");
  } else {
    router.push("/");
  }
  return (
    <>
      <h1>Secret</h1>
    </>
  );
};

但我收到此错误:未找到路由器实例。您应该只在应用程序的客户端内使用“next/router”。 任何人都知道如何解决它?谢谢!

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    我认为问题出在您放置代码的位置。您的情况应该是在安装组件时发生的,所以试试这个:

    React.useEffect(() => {
     if (token.token == null || token.token.hasOwnProperty("error")) {
        router.push("/login");
      } else {
        router.push("/");
      }
    }, [])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      • 2016-01-24
      • 2020-01-24
      相关资源
      最近更新 更多