Jea*_*non 5 javascript reactjs next.js
在我的 NextJS 应用程序中,我有一个在每个页面上都可见的语言选择器。当我选择一种新语言时,我只想通过lang=en向其附加查询参数来替换当前 URL 。
这是替换 URL 的函数:
const changeLanguage = (lang: LanguageID) => {
replace({
pathname,
query: { ...query, lang },
});
};
Run Code Online (Sandbox Code Playgroud)
在本例中replace,query和pathname来自下一个路由器。
现在,一切都适用于静态路由,但我无法使其适用于动态路由。例如,我有以下文件夹结构:
pages
|_customers
|__index.tsx
|__[customerId].tsx
Run Code Online (Sandbox Code Playgroud)
如果我打开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。
现在,我知道我可以asPath在路由器上使用,并通过附加lang到它来重建查询字符串对象,但我觉得它应该构建到 Next.js 中。另外,我知道使用 vanilla JS 可以轻松完成,但这不是重点。
我错过了什么吗?是否有更简单的方法将查询参数附加到动态路由而不进行服务器端重新渲染?
谢谢
Mac*_*ora 31
该解决方案不需要发送整个先前的路由,只需replace替换我们需要替换的内容,因此查询参数:
const router = useRouter();
router.replace({
query: { ...router.query, key: value },
});
Run Code Online (Sandbox Code Playgroud)
FDi*_*isk 16
如果我们想将其作为链接 - 像这样使用它:
// ...
const { query } = useRouter();
// ...
<Link
href={{
pathname: router.pathname,
query: { ...query, lang },
}}
passHref
shallow
replace
></Link>
Run Code Online (Sandbox Code Playgroud)
小智 9
我尝试将我的参数添加到路由查询中并推送路由器本身,如此处所述,它有效,但我收到了很多警告:

因此,我然后推送/并传递了我的查询参数,如下所示:
const router = useRouter();
router.push({ href: '/', query: { myQueryParam: value } });
Run Code Online (Sandbox Code Playgroud)
我希望这也适合你。
当您在 Next.js 中有动态路由并且想要对路由进行浅层调整以反映更新的查询参数时,另一种方法是尝试:
const router = useRouter()
const url = {
pathname: router.pathname,
query: { ...router.query, page: 2 }
}
router.push(url, undefined, { shallow: true })
Run Code Online (Sandbox Code Playgroud)
这将检索当前路径 ( router.pathname) 和查询 ( router.query) 详细信息,并将它们与新的page查询参数合并。如果您忘记合并现有的查询参数,您可能会看到如下错误:
提供的 href 值缺少需要正确插值的查询值
只需向当前路由器添加更多参数,然后自行推送
const router = useRouter();
router.query.NEWPARAMS = "VALUE"
router.push(router)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8954 次 |
| 最近记录: |