我试图为 Redux Action 函数实现 i18n 本地化,但我不断收到不同的钩子错误。当我以这种方式实现 i18n 时,我收到错误消息。
第 428:17 行:在既不是 React 函数组件也不是自定义 React Hook 函数的函数“sendDataRequest”中调用了 React Hook“useTranslation”。
import { useTranslation } from "react-i18next";
export const sendDataRequest = (requestId) => {
const { t } = useTranslation();
return async (dispatch) => {
try {
dispatch(sendDataRequest());
await dataAPI.sendDataRequest({ requestId });
notification.success({
message: t('infoPage.requestSentSuccessfully'),
});
dispatch(sendDataSuccess());
} catch (error) {
dispatch(sendDataFailure());
console.error(error);
}
}
}
然后我将 const { t } = useTranslation(); 移到 return 语句中。 但后来我收到另一个错误 看起来我显然在这里使用它是错误的。 但是我找不到任何关于在 Actions 中使用 i18n 的例子。 有谁知道甚至可以在 Actions 中使用 i18b 吗?
查看https://github.com/i18next/react-i18next/issues/909
您需要访问您的
i18next
实例。您在代码库中某处创建的那个。使用此实例,您只需调用 i18n.t("my.translation.key")
即可进行翻译。这完全独立于反应。
是的,这是可能的。
你需要在你的 actions/reducer 中导入你的 i18n 实例:
从 '../i18n_init_file' 导入 i18n;
之后你可以像这样在你的动作中使用实例:
i18n.t('STRING_TO_TRANSLATE');
或
i18n.changeLanguage('NEW_LOCALE').then();