【发布时间】:2020-02-15 12:42:16
【问题描述】:
首先我想说的是,我对 React 和 ES6 总体来说还比较陌生。
到目前为止,我已经在组件方面取得了巨大成功的 react-i18next。我还添加了 i18next-scanner 以自动将翻译键提取到 .json 文件。
我有一个 router/index.js 文件,其中包含我的项目的路线。该文件还用于创建侧边栏导航。
在这个文件中,我有用于侧边栏导航的名称。路由存储为可能包含子路由的对象。我的问题是我想使用 i18next t() 函数来翻译这些名称。
我的代码
i18n.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
路由/index.js:
// 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> 组件生成字符串感觉不对。设置空字符串并在以后使用 Promise 覆盖它们一点也不优雅。
我希望仍然能够使用扫描仪提取密钥。这使得传递密钥以便稍后与侧边栏组件中的t() 函数一起使用的解决方案很麻烦。扫描器不会使用变量获取动态翻译。
我的问题
我错过了什么?一个合适的 promise 解决方案应该是怎样的?在组件之外翻译字符串的正确方法是什么?
我可能想错了。但是就像我在介绍中所说的那样,我不是一个经验丰富的 JS/React 开发人员,而且我对 Promise 的先前知识和经验是有限的。我觉得我使用 Promise 的解决方案被错误地实现了。而且我希望密钥提取器可以扫描最终解决方案。
当用户使用i18n.changeLanguage(lng) 更改语言时,在组件外部生成的翻译键不会更新。更新这些的最佳方法是什么?
非常感谢所有反馈和帮助。
【问题讨论】:
标签: reactjs i18next react-i18next