在next-i18next库中更改语言时遇到CORS

时间:2020-04-19 12:34:39

标签: localization next.js i18next next-i18next

当我使用i18n.changeLanguage函数更改语言时,我有问题。我有两个具有onClick方法的按钮,并调用了一个名为changeLang的自定义函数。在该函数中,我正在调用i18n.changeLanguage函数并将其传递给lng参数


    const changeLang = lng => {
      i18n.i18n.changeLanguage(lng);
    };


    <button onClick={() => changeLang('en')} className="en">
       EN
    </button>
    <button onClick={() => changeLang('tr')} className="tr">
       TR
    </button>

enter image description here

我的i18n配置就是这样。

import NextI18Next from 'next-i18next';
import { initReactI18next } from 'react-i18next';

export default new NextI18Next({
  use: [initReactI18next],
  defaultLanguage: 'tr',
  fallbackLng: 'en',
  otherLanguages: ['en'],
  localeSubpaths: {
    en: 'en',
  },
  localePath: '/app/static/locales',
  detection: {
    order: ['cookie', 'localStorage'],
    lookupCookie: 'next-i18next',
    lookupLocalStorage: 'i18nextLng',
    caches: ['cookie', 'localStorage'],
  },
});

2 个答案:

答案 0 :(得分:0)

在lib的source code中,默认localePath的值为public/static/locales

请注意,因为它没有第一个斜杠,请尝试将其删除。

答案 1 :(得分:0)

我得到了错误。这里是正确的版本。我在其中添加了后端对象和loadPath,它解决了这个问题。

import NextI18Next from 'next-i18next';
import { initReactI18next } from 'react-i18next';

export default new NextI18Next({
  use: [initReactI18next],
  defaultLanguage: 'tr',
  fallbackLng: 'en',
  otherLanguages: ['en'],
  localeSubpaths: {
    en: 'en',
  },
  localePath: '/app/static/locales',
  detection: {
    order: ['cookie', 'localStorage'],
    lookupCookie: 'next-i18next',
    lookupLocalStorage: 'i18nextLng',
    caches: ['cookie', 'localStorage'],
  },
  backend: {
   loadPath: 'app/static/locales/{{lng}}/{{ns}}.json',
  }
});