NextJS - 将查询参数附加到动态路由 [英] NextJS - Appending a query param to a dynamic route
问题描述
在我的 NextJS 应用程序中,我有一个在每个页面上都可见的语言选择器.当我选择一种新语言时,我只想通过向其附加查询参数 lang=en
来替换当前 URL.
In my NextJS app, I have a language selector that's visible on every page. When I select a new language, I just want to replace the current URL by appending a query param lang=en
to it.
这是替换 URL 的函数:
Here's the function that replaces the URL:
const changeLanguage = (lang: LanguageID) => {
replace({
pathname,
query: { ...query, lang },
});
};
在本例中,replace
、query
和 pathname
来自下一个路由器.
In this example, replace
, query
and pathname
are coming from the next router.
现在,一切都适用于静态路由,但我无法使其适用于动态路由.例如,我有以下文件夹结构:
Now, everything works for static routes, but I'm unable to make it work for dynamic routes. For example, I have the following folder structure:
pages
|_customers
|__index.tsx
|__[customerId].tsx
如果我在 http://localhost/customers
上并将语言更改为英语,则 URL 将更改为 http://localhost/customers?lang=en代码> 这就是我想要的.但是,如果我在
http://localhost/customer/1
上并将语言更改为英语,则 URL 将更改为 http://localhost/customers/[customerId]?customerId=1&lang=en
,而不是我期望的 URL http://localhost/customers/1?lang=en
.
If I'm on http://localhost/customers
and I change my language to English, the URL changes to http://localhost/customers?lang=en
which is what I want. However, if I'm on http://localhost/customer/1
and I change my language to English, the URL changes to http://localhost/customers/[customerId]?customerId=1&lang=en
, instead of the URL I'm expecting http://localhost/customers/1?lang=en
.
现在,我知道我可以在路由器上使用 asPath
,并通过将 lang
附加到它来重构查询字符串对象,但我觉得这是应该的被构建到 Next 中.另外,我知道使用 vanilla JS 可以轻松完成,但这不是重点.
Now, I know that I could use asPath
on the router, and reconstruct the query string object by appending lang
to it, but I feel that it's something that should be build into Next. Also, I know it could be easily done with vanilla JS, but it's not the point here.
我错过了什么吗?有没有更简单的方法将查询参数附加到动态路由而不进行服务器端重新渲染?
Am I missing something? Is there an easier way to append query params to a dynamic route without doing a server-side re-rendering?
谢谢
推荐答案
只需在当前路由器上添加更多参数,然后自行推送
Just add more param to current router then push itself
const router = useRouter();
router.query.NEWPARAMS = "VALUE"
router.push(router)
这篇关于NextJS - 将查询参数附加到动态路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!