如何在 React 中不使用 hook 来使用 i18n 翻译?

Bab*_*abu 7 react-native react-redux react-i18next

我需要在我的中间件(import { Middleware } from 'redux')逻辑中进行翻译,但我不能使用useTranslation钩子(import { useTranslation } from 'react-i18next')。您如何标准解决这种情况?

\n

错误信息:

\n
React Hook "useTranslation" is called in function "myFunction: Middleware<{}, RootStateType>" which is neither a React function component or a custom React Hook function.\n
Run Code Online (Sandbox Code Playgroud)\n

我的代码(缩短):

\n
import PushNotificationIOS from '@react-native-community/push-notification-ios';\nimport { Middleware } from 'redux';\nimport { getType } from 'typesafe-actions';\n\nconst scheduleNotificationSettings = (notification: NotificationT): void => {\n PushNotificationIOS.scheduleLocalNotification({\n        fireDate: notification.startDate,\n        alertTitle: TRANSLATE_SOMEHOW(notification.titleKey),<--- ! HERE ! \xc2\xaf\\_(\xe2\x80\xaf\xe2\x9d\x9b\xe2\x80\xaf\xcd\x9c\xca\x96 \xef\xb8\xa1\xe2\x9d\x9b)_/\xc2\xaf\n        alertBody: TRANSLATE_SOMEHOW(notification.bodyKey),  <--- ! HERE !\n        alertAction: 'view',\n        isSilent: false,\n        repeatInterval: 'week',\n      });\n};\n\nexport const handleAction: Middleware<{}, RootStateType> = () => {\n  return next => {\n    return action => {\n      const result = next(action);\n      switch (action.type) {\n        case getType(create): {\n          createNotification(action.payload);\n          break;\n        }\n        case getType(delete): {\n          removeNotification(action.payload);\n          break;\n        }\n        default:\n          return result;\n      }\n      return result; //pass events to other middleware\n    };\n  };\n
Run Code Online (Sandbox Code Playgroud)\n

m_w*_*wer 21

我希望我正确理解你的问题,但我假设你已经初始化了 i18n,所以在 React 组件之外不要使用钩子,只需像这样导入它:

import i18n from 'i18next';
Run Code Online (Sandbox Code Playgroud)

然后使用它:

i18n.t(youri18nKey);
Run Code Online (Sandbox Code Playgroud)

  • 然后您可能需要等待 i18next 完成初始化。/sf/ask/4050484861/ (2认同)