NextJS - 将查询参数附加到动态路由

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)

在本例中replacequerypathname来自下一个路由器。

现在,一切都适用于静态路由,但我无法使其适用于动态路由。例如,我有以下文件夹结构:

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)

  • 它不仅替换查询参数,而且:“替换将阻止将新的 URL 条目添加到历史堆栈中。” (2认同)
  • 这为我解决了这个问题!使用所选答案给了我一个“未知密钥通过 urlObject 传递到 url.format”错误 (2认同)

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)

我希望这也适合你。


Arm*_*ghi 9

当您在 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 值缺少需要正确插值的查询值


Con*_*yen 8

只需向当前路由器添加更多参数,然后自行推送

const router = useRouter();
router.query.NEWPARAMS = "VALUE"
router.push(router)
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用**重写**,请务必小心,因为这种方法不起作用。这会将浏览器 url 更改为“pages”文件夹内重写 **指向** 的路径,而不是使用正确的 url。对我来说似乎是一个 nextjs 错误。 (5认同)
  • 肯定会导致问题 - 包括“通过 urlObject 传递未知密钥到 url.format”错误。 (5认同)
  • 我认为这种方法已经过时了 (4认同)