为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

人到中年有点甜 2022-07-21 10:12:10
在我的 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 可以轻松完成,但这不是重点。我错过了什么吗?有没有更简单的方法将查询参数附加到动态路由而不进行服务器端重新渲染?谢谢
查看完整描述

4 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

如果我们想把它作为一个链接 - 像这样使用它:


// ...

const { query } = useRouter();

// ...


<Link

    href={{

        pathname: router.pathname,

        query: { ...query, lang },

    }}

    passHref

    shallow

    replace

></Link>


查看完整回答
反对 回复 2022-07-21
?
红糖糍粑

TA贡献1815条经验 获得超6个赞

不需要发送整个先前路由的解决方案,replace只需替换我们需要替换的内容,因此查询参数:


const router = useRouter();

router.replace({

   query: { ...router.query, key: value },

});


查看完整回答
反对 回复 2022-07-21
?
富国沪深

TA贡献1790条经验 获得超9个赞

v

如果我们想把它作为一个链接 - 像这样使用它:


// ...

const { query } = useRouter();

// ...


<Link

    href={{

        pathname: router.pathname,

        query: { ...query, lang },

    }}

    passHref

    shallow

    replace

></Link>


查看完整回答
反对 回复 2022-07-21
?
开满天机

TA贡献1786条经验 获得超13个赞

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


const router = useRouter();

router.query.NEWPARAMS = "VALUE"

router.push(router)


查看完整回答
反对 回复 2022-07-21
  • 4 回答
  • 0 关注
  • 254 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号