首页 > 解决方案 > Routes.push() 在 NextJS 中没有按预期工作

问题描述

当用户尝试在未经身份验证的情况下访问应用程序的仪表板时,我试图将用户重定向到主页,但 Route.push() 不起作用。

我试图将 Router.push('/') 更改为 Router.push('/hey') -> 一个不存在的页面,这有效,路由改变了。此外,当我尝试访问像这样 Router.push('/auth/signin') 这样的路径时,它在 Router.push('/auth') 工作时不起作用

import { isAuthenticated } from "../helpers/auth";
import { Component } from "react";
import { Router } from "../routes";

class Ads extends Component {
  // static async getInitialProps(ctx) {
  //   if (ctx && ctx.req) {
  //     console.log(ctx);
  //     //ctx.res.writeHead(302, { Location: `/` });
  //     ctx.res.end();
  //   } else {
  //     console.log("client side");
  //     console.log(localStorage.getItem("auth-token"));
  //   }
  // }

  handleAuthentication = () => {
    if (localStorage.getItem("auth-token")) {
      return true;
    }
  };

  componentDidMount() {
    if (this.handleAuthentication()) {
      console.log("hey");
    } else {
      Router.pushRoute("/auth/signup");
    }
  }

  render() {
    return (
      <div>
        <p> Dashboard </p>
      </div>
    );
  }
}

export default Ads;

标签: reactjsroutestokennext.js

解决方案


看来您正在使用下一个路由器依赖项?

尝试使用next/router(来自 nextjs 的默认依赖项),它在我的代码中运行良好:

import Router from "next/router";

{ other code... }

Router.push("/auth/signup");

推荐阅读