【问题标题】:Routes.push() not working as expected at NextJSRoutes.push() 在 NextJS 中没有按预期工作
【发布时间】:2019-12-18 14:39:41
【问题描述】:

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

【问题讨论】:

    标签: reactjs routes token next.js


    【解决方案1】:

    您似乎在使用next-routerdependecy?

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

    import Router from "next/router";
    
    { other code... }
    
    Router.push("/auth/signup");
    

    【讨论】:

    • 现在我更改为 Router.push("/ads", "/"),并且 url 正在更改但没有重定向。这是我的仓库:github.com/LauraBeatris/befree-front
    • 你有没有试过加第三个参数shallow true?似乎您想使用别名,请阅读此处的文档github.com/zeit/next.js#shallow-routingRouter.push(href, as, { shallow: true })
    • 现在我这样做了:`componentDidMount() { const as = "/"; if (!localStorage.getItem("auth-token")) { Router.push("/ads", as, { shallow: true }); //window.location.reload(); } } ` 仍然只是将 url 更改为 localhost:3000/ads 到 localhost:3000,这就是我想要的,但页面仍然在同一个地方
    • 我正在尝试同样的问题,知道如何解决吗?
    • @user615274 你有什么问题?使用相同的 next-router 依赖项?
    【解决方案2】:

    我遇到了同样的问题并找到了解决方法,但不是解决方案。我用window.location

    //keep your base urls in a global variables file
    import { devUri, productionUri } from "../globalVariables";
    
    
    push = (route = "") => {
      const uri = process.env.NODE_ENV === "production" ? productionUri : devUri;
      window.location = uri + '/' + route
    }
    
    
    push("/auth/signup")
    push("/path/to/whatever/route/you/like")
    push() //navigates to your base uri

    }

    您可以将该函数保存到您的 globalVariables.js 版本中,并根据需要导入(与从 3rd 方模块导入其他函数的方式非常相似)

    import { devUri, productionUri, push } from "../globalVariables";

    顺便说一句,我遇到了与您完全相同的问题:Router.push("/") 或任何其他存在的地址似乎根本没有触发,Router.push("/unexistentlocation")正常工作

    【讨论】:

      【解决方案3】:

      这很好用,而且是一种干净而现代的方式(使用 Hooks)。

      步骤是:-

      1. 先导入
         import { useRouter } from 'next/router';
      
      1. 声明
         const router = useRouter();
      
      1. 使用它
         router.push('/search');
      

      例子

      import { useRouter } from 'next/router';
      
      const Banner = () => {
      
          const router = useRouter();
      
          const sendToSeachPage = () => {
              router.push('/search');
          };
      
      
         return ( .... )
      
      }
      

      【讨论】:

        猜你喜欢
        • 2022-12-31
        • 1970-01-01
        • 2014-01-26
        • 2021-10-19
        • 2020-03-18
        • 2012-06-14
        • 2014-11-15
        • 1970-01-01
        • 2012-07-02
        相关资源
        最近更新 更多