【问题标题】:Next.js change locale for the current path that has query, using routerNext.js 使用路由器更改具有查询的当前路径的语言环境
【发布时间】:2021-12-30 17:30:57
【问题描述】:

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

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,我会看到这个错误:

错误:提供的 href (/conference/[id]) 值缺少要正确插值的查询值 (id)。阅读更多:https://nextjs.org/docs/messages/href-interpolation-failed

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

【问题讨论】:

标签: javascript routes next.js


【解决方案1】:

这对我有用:

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

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

我从docs

请注意,要在保留所有路由信息(例如动态路由查询值或隐藏的 href 查询值)的同时仅处理语言环境切换,您可以将 href 参数作为对象提供:

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 })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多