網站搜尋

reactjs - 使用 react-i18next 的 useTranslationHooks 時出現 “i18next backendConnector: 載入命名空間失敗”


我正在嘗試在我的 create-react-app 應用程式中使用 useTranslation() 鉤子來實現 react-i18next。

然而,在控制台中,除錯模式顯示

i18next::backendConnector:載入語言 en 的命名空間 billingAddress 失敗,解析 /locales/en/billingAddress.json 為 JSON 失敗

和

i18next::translator: 缺少鍵 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

版本

"react": "^16.8.4",

"i18next": "^15.0.7",

我的翻譯文件

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

我的帳單地址檔案

  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>
)

我現在對如何載入命名空間感到有點困惑……有什麼想法嗎?

提前感謝你!

答案#1

你可以直接參考這裡的範例: https://github.com/i18next/react-i18next/tree/master/example/react/public/locales

使用 xhr 後端時,你需要提供有效的 JSON 文件作為來源——就是這樣。