Next.js带查询参数的当前路径切换locale如何避免参数重复报错
问题原因
你出现参数重复的核心原因是router.push同时传入了带占位符的pathname和全量query作为路径和as参数,Next.js会把已经填充到路径占位符中的参数再次拼接到查询字符串末尾,导致重复。而如果不传query又会因为动态路由占位符没有填充值抛出插值错误。
最优解决方案
直接使用router.asPath作为跳转目标即可,它是浏览器地址栏中实际显示的完整路径,已经完成了所有动态参数插值,同时保留了正常的查询参数,不会出现重复或缺失的问题:
import { useRouter } from 'next/router' const router = useRouter() const changeLocale = (selectedLocale) => { // 第三个参数传入目标locale,scroll: false可避免切换语言时页面滚动到顶部 router.push(router.asPath, router.asPath, { locale: selectedLocale, scroll: false }) } // 调用示例 <div onClick={() => changeLocale('fr')}>Fr</div>
适配Next.js 13+ App Router
如果你使用的是Next.js 13及以上版本的App Router客户端组件,可使用以下写法:
'use client' import { useRouter, usePathname, useSearchParams } from 'next/navigation' const changeLocale = (selectedLocale) => { const router = useRouter() const pathname = usePathname() const searchParams = useSearchParams().toString() const fullPath = searchParams ? `${pathname}?${searchParams}` : pathname // 替换路径中的locale前缀为目标locale const newPath = fullPath.replace(/^\/[^\/]+/, `/${selectedLocale}`) router.push(newPath, { scroll: false }) }
内容的提问来源于stack exchange,提问作者Hossein Fallah
相关产品推荐
相关产品推荐

