react-i18next设置失败,带有react-redux组件

时间:2019-11-05 21:30:47

标签: reactjs react-i18next

我已经尝试了所有方法来启用react-i18next,react-redux和Typescript应用。

下面是我的index.js文件:

 import * as enTranslations from "./assets/locales/en";
 import * as frTranslations from "./assets/locales/fr";
 const resources = {
 en: { messages: enTranslations }
 };

  i18next
 .use(initReactI18next)
 .init({
  resources,
  fallbackLng: "en",
  debug: true,

 // have a common namespace used around the full app
 ns: ["translations"],
 defaultNS: "translations",
 namespaceSeparator: '.',
 keySeparator: false, // we use content as keys
 interpolation: {
   escapeValue: false
 },
 lng: "en",

 }).then(() => {
 ReactDOM.render(
  <I18nextProvider i18n={i18next}>
    <Provider store={store}>
      <CookiesProvider>
        <App />
      </CookiesProvider>
    </Provider>
  </I18nextProvider>,
  document.getElementById('root')
 )
});

我的app.js代码:

 export default compose(withTranslation("translations"), connect(
 mapStateToProps,
 mapDispatchToProps
 ))(App);

我的组件渲染方法和导出代码:

export default compose(
withTranslation('translations'),
connect(mapStateToProps, mapDispatchToProps)
 )(UserComponent);

渲染方法:

render() {
const { t } = this.props;
return (
    <h1>{CLIENTS_HEADER_TITLE} {t('title')}</h1>
);

但是我总是看到打印的键而不是键值。我没有找到任何使用react-redux的示例。

我正在使用“ react-i18next”:“ ^ 11.0.1”,并且丢失了密钥错误。

1 个答案:

答案 0 :(得分:1)

下面的代码更改使其立即可用。

我的app.js代码:

 export default compose(withTranslation(), connect(
 mapStateToProps,
 mapDispatchToProps
 ))(App);

我的组件导出代码:

export default compose(
withTranslation(),
connect(mapStateToProps, mapDispatchToProps)
 )(UserComponent);

将init移至文件i18n.js:

   import enTranslations from "./assets/locales/en";

    const resources = {
      en: {
        translation: {
          "title": "Welcome  {{name}}"
        }
      }
    };

    i18n
      .use(initReactI18next)
      .init({
        resources,
        lng: "en",
        keySeparator: "false",
        debug: true,
        interpolation: {
          escapeValue: false
        },
        useDataAttrOptions: true
      });

    export default i18n;

调试控制台的输出可帮助我解决问题。

 //import enTranslations from '....'
 {title: "Welcome  {{name}}", intro: "To get started and save to reload."}

 //import * as enTranslations from '....'
 Module {default: {…}, __esModule: true, Symbol(Symbol.toStringTag): 
 "Module"}
  default: {title: "Welcome  {{name}}", intro: "To get started and save to 
  reload."}
  Symbol(Symbol.toStringTag): "Module"
 __esModule: true