使用next/router获取locale变量时出现Next Router未挂载错误
解决Next.js中获取locale/locales的路由钩子兼容问题
你遇到的核心问题是Pages Router和App Router的路由工具不兼容:
- 从
next/router引入useRouter是Pages Router的用法,要是在App Router(app/目录)里使用,就会触发"Next Router未挂载"错误; - 换成
next/navigation的useRouter(App Router专属)后,这个钩子本身就不带locale和locales属性,自然拿不到对应值。
下面分两种项目架构给出解决方案:
如果你用的是Pages Router(pages/目录)
直接用next/router的useRouter即可,注意钩子只能在客户端组件中调用,不能在服务端逻辑(比如getServerSideProps)里直接使用:
客户端组件内直接调用
import { useRouter } from 'next/router'; export default function MyPage() { const { locale, locales } = useRouter(); return ( <div> 当前语言:{locale} 支持的语言列表:{locales?.join(', ')} </div> ); }
服务端渲染场景(如getServerSideProps)
如果要在服务端获取locale,直接从context参数中提取即可,无需使用钩子:
export async function getServerSideProps(context) { const { locale, locales } = context; return { props: { locale, locales } }; } export default function MyPage({ locale, locales }) { return ( <div> 当前语言:{locale} 支持的语言列表:{locales.join(', ')} </div> ); }
如果你用的是App Router(app/目录)
App Router的useRouter(来自next/navigation)确实没有locale相关属性,需要用专门的国际化方案:
官方推荐方案:使用next-intl
Next.js官方推荐用next-intl处理多语言,它提供了直接获取locale的钩子:
- 先在
next.config.js中配置国际化规则:
const nextConfig = { i18n: { locales: ['en', 'zh-CN', 'ja'], defaultLocale: 'en', }, }; module.exports = nextConfig;
- 安装
next-intl后,在组件中调用钩子:
import { useLocale, useLocales } from 'next-intl'; export default function MyComponent() { const currentLocale = useLocale(); const allLocales = useLocales(); return ( <div> 当前语言:{currentLocale} 支持的语言:{allLocales.join(', ')} </div> ); }
无第三方库方案:解析路径获取locale
如果不想依赖第三方库,可以通过解析路径前缀来获取当前locale:
import { usePathname } from 'next/navigation'; // 从next.config.js中导入配置的语言列表 import { locales } from '../next.config'; export default function MyComponent() { const pathname = usePathname(); // 匹配路径中的语言前缀 const currentLocale = locales.find(lang => pathname.startsWith(`/${lang}/`)) || locales[0]; return ( <div> 当前语言:{currentLocale} 支持的语言:{locales.join(', ')} </div> ); }
重要提醒
不要在App Router中使用next/router的钩子,也不要在Pages Router中使用next/navigation的工具,两者完全不兼容,混用必然触发错误。
内容的提问来源于stack exchange,提问作者Subin Viju
相关产品推荐
相关产品推荐

