i18next.services.pluralResolver.addRule 返回 addRule 的未定义

2024-01-07

import i18next from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

const locales = ['en-GB', 'pl-PL'];
export const supportedLanguages = locales;

const localeResources = {
  'en-GB': {
    common: require('./locales/en-GB/common.json'),
  },
  'pl-PL': {
    common: require('./locales/pl-PL/common.json'),
  },
};

const frozenLocales = Object.freeze(locales);
export function localesImmutable() {
  return frozenLocales;
}

const fallbackLanguages = {
  pl: ['pl-PL'],
  default: ['en-GB'],
};

i18next.services.pluralResolver.addRule('pl', {
  numbers: [1, 2, 3],
  plurals: function (n) {
    return Number(
      n === 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2
    );
  },
});

const i18n = i18next;
i18n.use(LanguageDetector).init({
  resources: localeResources,
  fallbackLng: fallbackLanguages,
  ns: 'common',
  defaultNS: 'common',
  react: { wait: true },
  debug: false,
  cache: { enabled: true },
});

export default i18n;

我跟着这个link https://github.com/i18next/i18next/issues/1374覆盖我的项目的复数规则。 当我尝试推翻复数规则时,我做不到。pluralResolver似乎没有addRule方法。我明白了TypeError: Cannot read property 'addRule' of undefined。我缺少什么?翻译是波兰语复数形式。


你应该打电话addRule only after the init已经完成了。

i18n
  .use(LanguageDetector)
  .init({
    resources: localeResources,
    fallbackLng: fallbackLanguages,
    ns: 'common',
    defaultNS: 'common',
    react: { wait: true },
    debug: false,
    cache: { enabled: true },
  })
  .then(() => {
    // this called after the init finished
    i18n.services.pluralResolver.addRule('pl', {
      numbers: [1, 2, 3],
      plurals: function (n) {
        return Number(
          n === 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2
        );
      },
    });
  });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

i18next.services.pluralResolver.addRule 返回 addRule 的未定义 的相关文章

随机推荐