reactjs - Routes.push() 在 NextJS 上没有按预期工作

标签 reactjs routes token next.js

当用户尝试在未经身份验证的情况下访问应用程序的仪表板时,我试图将用户重定向到主页,但 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;

最佳答案

看来您正在使用 next-router依赖?

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

import Router from "next/router";

{ other code... }

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

关于reactjs - Routes.push() 在 NextJS 上没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57454034/

相关文章:

javascript - 在 React 中渲染 JavaScript 对象

gradle - 没有@@的任何字符串的Gradle replaceToken

c - 根据 C 中的几个设置词拆分字符串的最简单方法

c++ - 从 session ID 获取正确的 token

javascript - Reactjs 多个 if classNames

javascript - 在 React 中,如何从链接或其他组件添加 URL "string"作为对象的属性

javascript - 如何从另一个组件中清除一个组件的间隔函数?

javascript - 使用 angularjs 加载多个 View

php - 重定向到子文件夹中的 Controller 操作 - Laravel 4

javascript - 名为 `index` 错误的重复路由