router/index.js
I18N.JS:
t()
rutes/index.js:
// i18n.js
import i18next from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-xhr-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
const i18n = i18next
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
debug: true,
// ...
},
});
export { i18next }; // instance
export default i18n; // promise
问题 到目前为止,我已经提出了两种解决方案。但是感觉应该有一种更好的方法来实施这一点。使用
// routes/index.js
import React from 'react';
import i18n, { i18next } from 'i18n';
import { Trans } from 'react-i18next';
// other imports...
// Does not work since the translations aren't loaded yet.
const dashboardRoute = {
name: i18next.t('dashboard'),
path: '/',
component: MyPageComponent,
children: null,
};
// Solution 1: Trans component for generating strings
const dashboardRouteTrans = {
name: <Trans i18nKey="dashboard" />,
path: '/',
component: MyPageComponent,
children: null,
};
// Solution 2: Use promise to rewrite string
const dashboardRoutePromise = {
name: '', // Init with empty string
path: '/',
component: MyPageComponent,
children: null,
};
i18n.then(function(t) {
// Overwrite with translated string using promise
dashboardRoutePromise.name = t('dashboard');
});
export default [
dashboardRoute,
dashboardRouteTrans,
dashboardRoutePromise
];
组件生成字符串感觉不错。并设置空字符串并以后使用诺言完全没有优雅。 我希望仍然能够使用扫描仪提取键。这使得传递键的解决方案以后与侧栏组件中的
<Trans>
函数一起使用麻烦。扫描仪不会使用变量对动态翻译进行拾取。 我的问题
我想念什么?适当的承诺解决方案应该如何看?在组件之外翻译字符串的正确方法是什么?
我可能正在错误地考虑这一点。但是,就像我在介绍中所说的那样,我不是一个经验丰富的JS/React-Developter,而我对承诺的先验知识和经验也有限。我觉得我的使用诺言解决方案是错误地实施的。我希望最终的解决方案可以由钥匙提取器扫描。用户使用
t()
更改语言时,在组件之外生成的翻译键,请勿更新。更新这些更新的最佳方法是什么?
对所有反馈和帮助都非常感谢。
我发现了我认为是解决问题的好方法。实际上,在这种情况下,实际上无需使用该承诺。我可以通过两种方式解决这个问题:
1)重写
i18n.changeLanguage(lng)
以将
routes/index.js
函数作为参数。从渲染上的组件传递此功能(使用I18Next钩或HOC)。
2)在t()
中使用翻译键,然后将它们转换为组件中的渲染。为了能够扫描键,添加一个虚拟函数,该函数以键为参数并简单地返回它。将此功能添加到扫描仪中。这样做的一种方法是将以下内容添加到routes/index.js
i18n.js
如果任何人都有更好的解决方案或想解释如何正确使用I18Next返回的承诺,那么我全都是耳朵! :)
如果您需要在React之外使用I18Next,请选择正确的方法:
✔在调用t()之前确保初始化(等待initpromise)。
阅读有关它的更多信息