Next.js 使用路由器更改具有查询的当前路径的语言环境

Next.js change locale for the current path that has query, using router

我有一个更改语言环境的中心位置。我显示了一个语言环境列表,当用户点击其中任何一个时,我使用 useRouter 将用户重定向到 current 页面,但在选定的语言环境中:

var router = useRouter();

const changeLocale = (selectedLocal) => {
    router.push({
            pathname: router.pathname,
            query: router.query
        }, {
            pathname: router.pathname,
            query: router.query
        }, { locale });
}

<div onClick={() => changeLocale('fr')}>Fr</div>

对于没有参数的 URL 来说效果很好。但是当 URL 有参数时,它会被复制。例如,我有一个会议列表,当用户点击会议时,我会使用 Link:

将他带到会议页面
<Link
    href={{
        pathname: '/conference/[id]',
        query: { id: conf.id }
    }}

例如,这会将用户带到 example.com/conference/5。但是当用户更改该页面上的语言环境时,我看到 URL 更改为 example.com/conference/5?id=5。如您所见,我这里有两个重复的 id 参数。如果我不将 query 传递给 router.push,我会看到此错误:

Error: The provided href (/conference/[id]) value is missing query values (id) to be interpolated properly. Read more: https://nextjs.org/docs/messages/href-interpolation-failed

我应该如何有效地重新路由用户并保持 URL 结构和参数?

这对我有用:

    const changeLocale = (locale) => {
        router.push({
            route: router.pathname,
            query: router.query
        }, router.asPath, { locale });
    }

基本上我只改了router.push方法的第二个参数

我从docs:

Note that to handle switching only the locale while preserving all routing information such as dynamic route query values or hidden href query values, you can provide the href parameter as an object:

import { useRouter } from 'next/router'
const router = useRouter()
const { pathname, asPath, query } = router
// change just the locale and maintain all other route information including href's query
router.push({ pathname, query }, asPath, { locale: nextLocale })