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

在我的 NextJS 应用程序中,我有一个在每个页面上都可见的语言选择器。当我选择一种新语言时,我只想通过向其附加查询参数lang=en来替换当前 URL。


这是替换 URL 的函数:


const changeLanguage = (lang: LanguageID) => {

    replace({

      pathname,

      query: { ...query, lang },

    });

  };

在本例中replace,query和pathname来自下一个路由器。


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


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。


现在,我知道我可以asPath在路由器上使用,并通过附加lang到它来重构查询字符串对象,但我觉得它应该构建到 Next 中。另外,我知道使用 vanilla JS 可以轻松完成,但这不是重点。


我错过了什么吗?有没有更简单的方法将查询参数附加到动态路由而不进行服务器端重新渲染?


谢谢


人到中年有点甜
浏览 256回答 4
4回答

HUX布斯

如果我们想把它作为一个链接 - 像这样使用它:// ...const { query } = useRouter();// ...<Link&nbsp; &nbsp; href={{&nbsp; &nbsp; &nbsp; &nbsp; pathname: router.pathname,&nbsp; &nbsp; &nbsp; &nbsp; query: { ...query, lang },&nbsp; &nbsp; }}&nbsp; &nbsp; passHref&nbsp; &nbsp; shallow&nbsp; &nbsp; replace></Link>

红糖糍粑

不需要发送整个先前路由的解决方案,replace只需替换我们需要替换的内容,因此查询参数:const router = useRouter();router.replace({&nbsp; &nbsp;query: { ...router.query, key: value },});

富国沪深

v如果我们想把它作为一个链接 - 像这样使用它:// ...const { query } = useRouter();// ...<Link&nbsp; &nbsp; href={{&nbsp; &nbsp; &nbsp; &nbsp; pathname: router.pathname,&nbsp; &nbsp; &nbsp; &nbsp; query: { ...query, lang },&nbsp; &nbsp; }}&nbsp; &nbsp; passHref&nbsp; &nbsp; shallow&nbsp; &nbsp; replace></Link>

开满天机

只需向当前路由器添加更多参数,然后自行推送const router = useRouter();router.query.NEWPARAMS = "VALUE"router.push(router)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript