首页 > 解决方案 > react-i18next - 导入 i18n 实例并直接使用与使用 useTranslation 挂钩

问题描述

我有一个用 React & support hooks 编写的项目。我正在尝试使用 react-i18next 来支持翻译。一切正常,因为我遵循了文档。

t()但是,当我想在助手/非组件 .js 文件上使用该功能时,我偶然发现了一些问题。然后,我通过直接从./i18n.ts看起来像这样的 init 文件导入 i18n 来解决它

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

i18n
  .use(initReactI18next) 
  .init({
    resources,

    ns: [
      'common',
      'dashboard',
      'landing'
    ],
    defaultNS: 'common',

    fallbackLng: 'en',
    supportedLngs: ['de', 'en'],
    interpolation: {
      escapeValue: false, 
    },
  });

export default i18n;

我意识到我根本不需要使用钩子,因为我可以像这样在代码中的任何地方使用它,甚至在我的功能组件文件上

import i18n from "@root/i18n"

...
i18n.t('namespace:path')

我想知道如果您可以像这样导入它,为什么建议使用useTranslation钩子/ HOC?withTranslation我读到了useTranslation应用悬念,但似乎initReactI18next默认情况下也应用了悬念。

我很好奇不使用推荐的钩子/ HOC 是否有任何副作用?

标签: reactjsreact-i18next

解决方案


我在他们的 github 问题上找到了这个答案。

但是这些常量永远不会在 languageChange 上更新!所以要么:

update them to new language value based on event triggered by i18next: https://www.i18next.com/overview/api#onlanguagechanged
or better have only the keys in the constants and translate as close to the rendering as possible

推荐阅读