react-i18next-导入i18n实例并直接使用vs使用useTranslation钩子

问题描述

我有一个用React和support挂钩编写的项目。 我正在尝试使用react-i18next支持翻译。 按照我的说明文档,一切正常。

但是,当我想在助手/非组件.js文件上使用t()函数时,我偶然发现了一些问题。 然后,我通过直接从看起来像这样的初始化文件./i18n.ts中导入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钩子/ withTranslation HOC(如果您可以这样导入)? 我读到useTranslation适用于暂记,但initReactI18next似乎也认适用于暂记。

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

解决方法

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

但是这些常量永远不会在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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...