You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js:pages目录下_document.js获取locale遇路由未挂载错误

在Pages Router的_document.js中获取locale的正确方法

你遇到的问题核心在于:_document.js 是服务端渲染的根文档组件,不处于客户端路由上下文环境中,所以无法使用客户端路由钩子(useRouter)或App Router的导航API(next/navigation)。正确的做法是通过_document.js的getInitialProps方法在服务端获取locale。

具体实现步骤

  • 重写Document类的getInitialProps静态方法,从上下文参数中直接提取locale
  • 将获取到的locale作为props传递给Document组件,在render阶段使用

代码示例

import Document, { Html, Head, Main, NextScript } from 'next/document'

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    // 从上下文获取locale
    const { locale } = ctx
    return { ...initialProps, locale }
  }

  render() {
    const { locale } = this.props
    return (
      <Html lang={locale}>
        <Head>
          {/* 根据locale自定义头部内容,比如加载对应语言的资源 */}
          {locale === 'zh-CN' && <link rel="stylesheet" href="/styles/zh.css" />}
          {locale === 'en-US' && <link rel="stylesheet" href="/styles/en.css" />}
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

关键说明

  • getInitialProps在服务端执行(或首次客户端渲染),可以直接访问ctx.locale,这是Next.js在国际化配置后自动注入的上下文参数
  • 拿到locale后,你可以自定义<Html>的lang属性、加载对应语言的静态资源、添加不同的meta标签等

内容的提问来源于stack exchange,提问作者behnam rahmani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 02:01:16