简体   繁体   English

在 Next.js 中执行客户端重新加载和更改 url

[英]Do a client side reload and change url in Next.js

I have the following code snippet in one of my Next js components -:我的 Next js 组件之一中有以下代码片段 -:

import { useRouter } from "next/router";
import Router from "next/router";
import { Menu } from "antd";
export default function AccountMenuList() {
  const router = useRouter();
  function onClick({ key }) {
    switch (key) {
      case "my-account":
        router.push("/profile");
        break;
      case "my-wishlist":
        router.push("/wishlist");
        break;
      case "logout": {
        localStorage.removeItem("user");
        // Router.reload(window.location.pathname);
        router.reload();
        break;
      }
      default:
        break;
    }
  }
  return (
    <Menu onClick={onClick}>
      <Menu.Item key="my-account">MY ACCOUNT</Menu.Item>
      <Menu.Item key="my-wishlist">MY WISHLIST</Menu.Item>
      <Menu.Item key="logout">LOGOUT</Menu.Item>
    </Menu>
  );
}

In the app, I am on the '/profile' page and then I click on logout button.在应用程序中,我在“/profile”页面上,然后单击注销按钮。 What I want to do is to do a url change back to the home page '/' and do a client side reload as well.我想要做的是将 url 更改回主页 '/' 并进行客户端重新加载。 I know that a client side reload can be done with router.reload().我知道客户端重新加载可以通过 router.reload() 来完成。 But using it with router.push() does not change the url and the page itself.但是将它与 router.push() 一起使用不会更改 url 和页面本身。

Can anyone explain what I must be doing or thinking wrong?任何人都可以解释我必须做什么或思考错误吗?

In this case I would do a hard window.location="/" (or explicitly set your base URL instead of the slash).在这种情况下,我会做一个硬window.location="/" (或明确设置您的基本 URL 而不是斜杠)。 It will send the browser to that URL and reload the page as it does so.它会将浏览器发送到该 URL 并重新加载页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM