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

页面刷新时i18n语言初始显示undefined后加载正确语言的问题求助

页面刷新时i18n语言初始显示undefined后加载正确语言的问题求助

大家好,我在Next.js项目里用i18next做国际化的时候遇到了个棘手的问题——每次刷新页面,都会先短暂显示"undefined",之后才会切换到正确的翻译内容。我已经对着代码翻来覆去查了好半天,试过各种调试,但还是没搞定,想请各位大佬帮忙看看问题出在哪。

先贴一下我当前的国际化相关代码:

import i18next from 'i18next';
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import { initReactI18next } from 'react-i18next';
import { applyClientHMR } from 'i18next-hmr/client';
import LanguageDetector from 'i18next-browser-languagedetector';
import Backend from 'i18next-http-backend';
import i18n from 'i18next';
import intervalPlural from 'i18next-intervalplural-postprocessor';
import { uniq } from 'lodash';
import header from '../public/static/locales/en/header.json';

const defaultNamespaces = [
  'header',
];

interface Translation {
  [key: string]: string;
}

interface Translations {
  [namespace: string]: Translation;
}

export interface I18nResources {
  translations: Translations;
  namespaces: string[];
}

type LocaleSetupProps = {
  i18nResources?: I18nResources;
  fallback?: string;
};

export default function useNextLocale({
  i18nResources = { translations: {}, namespaces: [] },
}: LocaleSetupProps) {
  const router = useRouter();
  console.log(router.locale);
  console.log(i18n.language);

  const { translations, namespaces } = i18nResources;
  const locale = router.locale;
  const namespacesWithDefaults = uniq([...namespaces, ...defaultNamespaces]);

  if (!i18n.isInitialized) {
    i18n
      .use(intervalPlural)
      .use(initReactI18next)
      .use(Backend)
      .use(LanguageDetector)
      .init({
        lng: locale,
        preload: locale ? [locale] : [],
        ns: namespacesWithDefaults,
        supportedLngs: router.locales,
        fallbackLng: 'en',
        react: { useSuspense: false },
        debug: process.env.NODE_ENV !== 'production',
        load: 'all',
        backend: {
          loadPath: '/static/locales/{{lng}}/{{ns}}.json',
        },
        saveMissing: process.env.NODE_ENV !== 'production',
      });

    if (process.env.NODE_ENV !== 'production') {
      applyClientHMR(i18n);
    }
  }

  i18n.setDefaultNamespace(namespaces[0]);

  if (locale) {
    if (!i18next.language) {
      i18next.changeLanguage(locale);
    }

    namespacesWithDefaults.forEach((ns) => {
      if (!i18next.hasResourceBundle(locale, ns)) {
        i18next.addResourceBundle(locale, ns, translations[ns]);
      }
    });
  }

  return { locale };
}

export async function getTranslations(
  locale: string | undefined,
  namespaces: string[],
) {
  const translations: Translations = {};
  const namespacesWithDefaults = uniq([...namespaces, ...defaultNamespaces]);

  for (const ns of namespacesWithDefaults) {
    const { default: data = {} }: { default: Translation } = await import(
      `../public/static/locales/${locale}/${ns}.json`
    );
    translations[ns] = data;
  }

  return { translations, namespaces: namespacesWithDefaults };
}

我观察到的现象是:页面刷新时,控制台打印的router.locale和i18n.language其中有一个会先出现undefined,过一小会儿才会变成正确的语言值,这应该就是页面先显示undefined的原因。我试过调整初始化的顺序、检查资源文件路径、确认语言检测逻辑,但都没能解决这个短暂显示undefined的问题。

有没有朋友遇到过类似的情况?或者能帮我指出代码里可能存在的问题?麻烦大家了!

备注:内容来源于stack exchange,提问作者dsg15

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 13:30:26