使用react-i18next时,“i18next backendConnector:加载命名空间失败”useTranslationHooks

问题描述 投票:1回答:1

我正在尝试使用useTranslation()钩子在我的create-react-app应用程序上实现react-i18next。

但是,在控制台中,调试模式显示

i18next :: backendConnector:加载命名空间billingAddress语言en失败无法解析/locales/en/billingAddress.json到json

i18next :: translator:missingKey en billingAddress Form.email客户电子邮件(默认)

i18next.ts

import {initReactI18next} from "react-i18next";
import i18next from "i18next";
import LanguageDetector from 'i18next-browser-languagedetector';
import Backend from 'i18next-xhr-backend';
import XHR from "i18next-xhr-backend";

i18next
// .use(Backend)
    .use(LanguageDetector)
    .use(XHR)
    .use(initReactI18next) // passes i18n down to react-i18next
    .init({
        lng: "en",
        fallbackLng: {
            'en-US':['en'],
            'zh-CN':['cn'],
            default:['en']
        },
        debug: true,
        ns: ['billingAddress'],
        defaultNS: 'billingAddress',
        // load: "currentOnly",
        interpolation: {
            escapeValue: false // react already safes from xss
        },
        keySeparator: false,
        // backend: {
        //     loadPath: "/locales/{{lng}}/{{ns}}.json",
        //     crossDomain: true
        // },
        react: {
            wait: true,
        }
    });

export default i18next;

├── src
│   ├── i18next.ts
│   ├── locales
│   │   ├── cn
│   │   │   └── billingAddress.ts
│   │   └── en
│   │       └── billingAddress.ts
│   ├── index.tsx

“反应”:“^ 16.8.4”,

“i18next”:“^ 15.0.7”,

我的翻译文件

export default{
  "Form": {
    "emailLabel": "customer Email",
    "emailPlaceholder": "[email protected]",
  }
}

我的billingAddress文件

  const [t, i18n] = useTranslation();

    const changeLanguage = (language: string) => (e: React.MouseEvent) => {
        i18n.changeLanguage(language)
    };

const someValues: billingAddress = {
emailLabel: t("Form.emailLabel","Customer Email")
}

return (
<div>
 <button onClick={changeLanguage("en")}>English</button>
<OtherComponent value={someValues} />
</div>
)

我现在很混淆如何加载命名空间......任何想法?

提前致谢!

reactjs typescript react-hooks i18next react-i18next
1个回答
0
投票

您可以在这里关注示例:https://github.com/i18next/react-i18next/tree/master/example/react/public/locales

使用xhr后端,您需要提供有效的JSON文件作为源 - 这就是全部。

© www.soinside.com 2019 - 2024. All rights reserved.