NextJS-将查询参数附加到动态路由 [英] NextJS - Appending a query param to a dynamic route

查看:28
本文介绍了NextJS-将查询参数附加到动态路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的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 = zh_CN ,而不是我期望的URL http://localhost/customers/1?lang = zh_CN .

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?

谢谢

推荐答案

我最终使用了我首先要避免的解决方案,那就是使用 asPath 值.至少,由于路径相同,因此无需进行服务器端重新渲染.

I ended up using the solution that I wanted to avoid in the first place, which was to play with the asPath value. Atleast, there's no server-side re-rendering being done since the path is the same.

这是我更新的 changeLanguage 函数( stringifyUrl 来自 query-string 包)

Here's my updated changeLanguage function (stringifyUrl is coming from the query-string package)

  const changeLanguage = (lang: LanguageID) => {
    const newPathname = stringifyUrl({ url: pathname, query: { ...query, lang } });
    const newAsPath = stringifyUrl({ url: asPath, query: { lang } });
    replace(newPathname, newAsPath);
  };

这篇关于NextJS-将查询参数附加到动态路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆