reactjs - 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 是否有任何副作用?
解决方案
我在他们的 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
推荐阅读
- javascript - 如何通过在js中单击刷新关键帧动画?
- browser - 如何检测是否有人在没有有效客户端证书的情况下尝试访问我的网站?
- javascript - 如何正确传递参数?
- codeigniter - 无法使用重置密码表单重置管理员密码
- azure-active-directory - Microsoft Graph API - Azure AD Connect - extensionAttribute
- xamarin - 在地图中突出显示建筑物
- python - 如何更改 is_actual (DRF) 的布尔值
- reactjs - React Hooks:函数仍然有旧状态?
- python - Django:如何在管理员中创建管理员“计算列表”,例如 BMI、体表、年龄
- julia - 如何在 Julia 中定义我们自己的类型?