You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js Router中window.location.pathname等效方法及保留查询参数实现

问题解答

1. 切换路径时保留查询字符串参数

你可以使用router.push的对象参数语法,直接复用当前路由的查询参数:

import router from "next/router";

// 保留现有查询参数跳转到/login页面
router.push({
  pathname: "/login",
  query: router.query // 直接传递当前的查询参数对象
});

如果需要在保留原有参数的同时新增/修改部分参数,用对象展开运算符即可:

// 保留原有参数,同时添加新的参数newKey
router.push({
  pathname: "/login",
  query: { ...router.query, newKey: "newValue" }
});

2. Next.js Router中对应window.location.pathname的等效方法

Next.js Router提供了router.pathname属性,它和原生的window.location.pathname功能完全一致,用于获取当前页面的路径名:

import router from "next/router";

// 输出当前路径名,例如 "/dashboard" 或 "/login"
console.log(router.pathname);

内容的提问来源于stack exchange,提问作者GorvGoyl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 16:55:02