为什么反应 i18next 不工作?没有错误

Why is react i18next not working ? no errors

翻译不工作我只看到钥匙。我没有“欢迎来到 MySite”,而是只有“welcome.title MySite”。

我的i18nextConf.js文件

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

const fallbackLng = ['fr'];
const availableLanguages = ['en','fr'];

i18n
    .use(Backend) // load translations using http (default public/assets/locals/en/translations)
    .use(LanguageDetector) // detect user language
    .use(initReactI18next) // pass the i18n instance to react-i18next.
    .init({
        fallbackLng, // fallback language is english.
        backend: {
            /* translation file path */
            // loadPath: './translations/{{lng}}/{{ns}}.json'
            loadPath: './translations/{{lng}}/common.json'
        },

        detection: {
            checkWhitelist: true, // options for language detection
        },

        debug: false,

        whitelist: availableLanguages,

        interpolation: {
            escapeValue: false, // no need for react. it escapes by default
        },
    });

export default i18n;

我的index.js文件

import React,{ Suspense } from 'react';
import './i18nextConf';

// code omitted

ReactDOM.render(
    <React.StrictMode>
        <Provider store={store}>
            <Suspense fallback={null}>
                <App />
            </Suspense>
        </Provider>
    </React.StrictMode>,
    document.getElementById('root')
);

我的翻译文件在 src/translations/en/common.jsonsrc/translations/fr/common.json

{
    "welcome": {
        "title": "Welcome to "
    }
}

我的CustomComponent.js

import React,{ Component } from 'react';
import { withTranslation } from "react-i18next";
class CustomComponent extends Component {
    render() {
        const { t } = this.props;

        return (
            <div className="section-title">
                <h2 className={classes.myTitle}>{t('welcome.title')}</h2>
            </div>
        );
    }
}

export default withTranslation()(CustomComponent);

我的配置有问题吗?我需要更改什么?

这些翻译文件将从您的 index.html 也被加载的基本路径提供,如果它是使用 create-react-app 创建的应用程序,则该文件夹是 public.

所以我认为当你在 loadPath 中说从 ./translations/{{lng}}/common.json 加载文件时,请求实际上被解析为 public/translation/en/common.json 但你的文件位于 src.....正如你所说。

您可以尝试将这些文件移动到 public(检查 this example for reference also ) or you can try the other syntax where you explicitly import the json from each file (inside src) and add it to a resources object which you pass to configuration as shown here