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

React-i18next加载API翻译数据后t函数不生效问题求助

问题:i18next调用API加载翻译后,t函数返回键名而非翻译值

我通过以下代码从API获取翻译数据,API调用已成功,控制台显示翻译资源已加载,但使用useTranslation的t函数(如t('Verify'))时,返回的是键名“Verify”而非预期的翻译值“Vérifier”。

我的代码:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';

import axios from 'axios';
import { BASE_URL } from './utils/Url';

const loadResources = async (locale) => {
    let contUrl = BASE_URL + '/translation';
    return await axios
        .post(contUrl, {
            lang: 'fr-ca',
            type: 'json',
            location: 'msdemo',
            country: 'CA',
        })
        .then((response) => {
            return response.data.translation_data;
        })
        .catch((error) => {
            console.log(error);
        });
};

const backendOptions = {
    loadPath: "{{lng}}|{{ns}}",
    request: (options, url, payload, callback) => {
        try {
            const [lng] = url.split('|');
            loadResources(lng).then((response) => {
                console.log('response', response);
                callback(null, {
                    data: response,
                    status: 200,
                });
            });
        } catch (e) {
            console.error(e);
            callback(null, {
                status: 500,
            });
        }
    },
};

i18n.use(LanguageDetector)
    .use(Backend)
    .init({
        backend: backendOptions,
        fallbackLng: 'en',
        debug: true,
        load: 'languageOnly',
        ns: ['translations'],
        defaultNS: 'translations',
        keySeparator: false,
        interpolation: {
            escapeValue: false,
            formatSeparator: ',',
        },
        react: {
            wait: true,
        },
    });

export default i18n;

API返回的翻译数据示例:

{
  "Verify": "Vérifier",
  "WELCOME": "BIENVENUE",
  "ewallet": "Portefeuille électronique",
  "testing": "Test"
}

问题原因

  1. 资源结构不符合i18next要求:i18next期望的资源格式是{ [命名空间]: { [键]: 翻译值 } },但当前直接返回了键值对对象,没有包裹在配置的默认命名空间translations下。
  2. 硬编码请求语言:loadResources函数里固定使用lang: 'fr-ca',没有使用传入的locale参数,导致语言检测器的结果失效,可能加载的翻译和当前设置的语言不匹配。

修复方案

1. 修改loadResources函数,适配i18n资源结构并使用动态locale

const loadResources = async (locale) => {
    let contUrl = BASE_URL + '/translation';
    try {
        // 使用传入的locale参数,而非硬编码
        const response = await axios.post(contUrl, {
            lang: locale,
            type: 'json',
            location: 'msdemo',
            country: 'CA',
        });
        // 将翻译数据包裹在默认命名空间translations下
        return { translations: response.data.translation_data };
    } catch (error) {
        console.log(error);
        // 出错时返回空的命名空间结构,避免i18next报错
        return { translations: {} };
    }
};

2. 验证语言检测器的输出

开启debug: true后,控制台会输出类似i18next::languageDetector detected: fr-CA的日志,确认检测到的语言和API支持的语言格式一致。如果API只接受不带地区的语言代码(如fr),可以在loadResources里处理locale:

// 取locale的前两位,比如把fr-CA转为fr
lang: locale.split('-')[0],

3. 确认初始化配置的命名空间匹配

当前配置的ns: ['translations']和defaultNS: 'translations'是正确的,确保返回的资源结构里的命名空间和这里一致即可。

修复后,调用t('Verify')就能正确返回翻译值Vérifier了。


内容的提问来源于stack exchange,提问作者Sarthak Gupta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 12:01:00