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
相关产品推荐
相关产品推荐

