react-i18next中的UseTranslation返回null

问题描述 投票:0回答:1

useTranslation()返回i18n的undefined。我不明白为什么。我花了很多时间来调试此问题。感谢您的帮助!enter image description here

reactjs i18next
1个回答
0
投票

由于我没有看到您的代码,对不起,这可能是在黑暗中摸索。

您需要在i18n的自定义位置和翻译字符串的位置导入一些文件。除非您在Main中进行此操作,否则不确定您在哪里。

即:translationUtils.js

import i18n from 'i18next';
import {initReactI18next} from 'react-i18next';

i18n.use(initReactI18next).init({

  lng: 'en',
  fallbackLng: 'en',

 resources: {
    en: {
      translation: {
        "myTranslationKey": "hello world"
      }
    }
  },

  keySeparator: false,
  interpolation: {
    escapeValue: false,
  },
});

export default i18n;

然后您需要将其导入文件(屏幕快照中的文件),即:

import './translationUtils';

然后您应该可以像这样使用它:

const {t} = useTranslation();

t("myTranslationKey", "default value");

您还需要确保您的react版本支持钩子。

© www.soinside.com 2019 - 2024. All rights reserved.