NEXT JS - 如何删除查询参数?

问题描述

如何在 Next JS (React) 中不刷新页面的情况下删除或更新查询参数?

  1. 用户在 URL /about?login=success&something=yes
  2. 单击按钮并从 URL 中删除 ?login=success&something=yes 而不刷新页面。点击按钮后的 URL 将是 /about

我怎样才能实现它?

正如 thread 中提到的,我知道可以使用 Router 删除查询参数或查询字符串。但是,useLocationuseHistorynext/router 上不可用。

解决方法

const router = useRouter();

router.replace("/about",undefined,{ shallow: true });

使用 replace 防止在历史记录中添加新的 URL 条目(否则只需使用 push),而 shallow: true 允许您change the URL without running data fetching methods。这将导致重新渲染,但不会刷新页面本身。

,

Nextjs 具有 useRouter 钩子,可用于以编程方式更改 url。 Link to the docs

,

根据History,您可以使用history.replaceState来实现这一点。

window.history.replaceState(null,'','/about')
,

我对类似问题的解决方案是:

push(`${asPath.split('?')[0]}?comp=${id}`);

或者如果你想拥有可重用的功能:


function delQuery(asPath) {
  return asPath.split('?')[0]
}

...
const {push,asPath} = useRouter()

push(`${delQuery(asPath)}?comp=${id}`);