gpt4 book ai didi

reactjs - 在组件外使用 react-i18next t 函数。正确使用 Promise 时遇到问题

转载 作者:行者123 更新时间:2023-12-03 19:23:39 30 4
gpt4 key购买 nike

首先我想说的是,我对 React 和 ES6 总体上比较陌生。

到目前为止,我已经在组件中实现了 react-i18next 并取得了巨大成功。我还添加了 i18next-scanner 以自动将翻译 key 提取到 .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 覆盖这些字符串一点也不优雅。

我希望仍然能够使用扫描仪提取 key 。这使得传递 key 的解决方案稍后与 t() 一起使用。功能在侧边栏组件比较麻烦。扫描器不会使用变量来获取动态翻译。

我的问题

我错过了什么?一个合适的 promise 解决方案应该是什么样子的?在组件之外翻译字符串的正确方法是什么?

我可能正在错误地考虑这个问题。但是就像我在介绍中所说的那样,我不是一个经验丰富的 JS/React 开发人员,我之前对 promise 的了解和经验是有限的。我觉得我使用 Promise 的解决方案被错误地实现了。我希望 key 提取器可以扫描最终解决方案。

当用户使用 i18n.changeLanguage(lng) 更改语言时,在组件外部生成的翻译键不会更新。更新这些的最佳方法是什么?

非常感谢所有反馈和帮助。

最佳答案

我找到了我认为可以很好地解决我的问题的方法。在这种情况下实际上没有必要使用 promise 。我可以通过两种方式解决这个问题:

1) 重写 routes/index.jst()函数作为参数。在渲染时从组件传递这个函数(使用 i18next hook 或 HOC)。

2) 使用 routes/index.js 中的翻译键并在组件中渲染时翻译这些。为了能够扫描键,添加一个将键作为参数并简单返回它的虚拟函数。将此功能添加到扫描仪。一种方法是将以下内容添加到 i18n.js文件。

export const tk = (key) => key;

如果有人有更好的解决方案或想解释如何正确使用 i18next 返回的 promise ,我全神贯注! :)

关于reactjs - 在组件外使用 react-i18next t 函数。正确使用 Promise 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58452182/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com