【问题标题】:Fetch locale from database instead of browser i18next从数据库而不是浏览器 i18next 中获取语言环境
【发布时间】:2020-05-10 13:39:08
【问题描述】:

我目前从用户的浏览器获取区域设置。用户现在可以在他们的配置文件中设置他们的首选语言,这存储在数据库中。我想从数据库中获取这个值并为i18next 设置正确的语言环境。我在这里读到了一些关于自己的检测功能的东西:https://github.com/i18next/i18next-browser-languageDetector。但我不完全确定这是否是正确的使用方法。我的 i18n.js 文件当前设置如下:

import i18n from 'i18next';
import Backend from 'i18next-xhr-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
import { reactI18nextModule } from 'react-i18next';
import moment from 'moment';

export const i18nInit = (callback = () => { }) =>
  // for easy overview use: https://devhints.io/moment its better than official docs:
  moment.defineLocale('nl-custom', {
    parentLocale: 'nl',
    longDateFormat: {
      LT: 'HH:mm',
      LTS: 'HH:mm:ss',
      L: 'D MMM', // need this format to display dates in past year(s)
      LL: 'D MMMM YYYY', // need this format to display dates in the current year
      LLL: 'YYYY-MM-DD HH:mm', // need this format as input for the date picker
      LLLL: 'dddd D MMMM YYYY HH:mm',
    },
  }) &&
  moment.defineLocale('en-custom', {
    parentLocale: 'en',
    longDateFormat: {
      LT: 'HH:mm',
      LTS: 'HH:mm:ss',
      L: 'MMM D',
      LL: 'MMMM D YYYY', // need this format to display dates in the current year
      LLL: 'YYYY-MM-DD HH:mm', // need this format as input for the date picker
      LLLL: 'MMMM dddd D YYYY HH:mm',
    },
  }) &&
  i18n
    // load translation using xhr -> see /public/locales
    // learn more: https://github.com/i18next/i18next-xhr-backend
    .use(Backend)
    // detect user language
    // learn more: https://github.com/i18next/i18next-browser-languageDetector
    .use(LanguageDetector)
    // pass the i18n instance to the react-i18next components.
    // Alternative use the I18nextProvider: https://react.i18next.com/components/i18nextprovider
    .use(reactI18nextModule)
    // init i18next
    // for all options read: https://www.i18next.com/overview/configuration-options
    .init(
      {
        fallbackLng: 'en',
        ns: ['actionpoints', 'common', 'menu', 'messages', 'overview', 'settings', 'shepherdTour', 'users', 'profile', 'meetingtypes'],
        defaultNS: 'common',
        whitelist: ['nl', 'en'],
        backend: {
          // Path where resources get loaded from, or a function
          // returning a path:
          // function(lngs, namespaces) { return customPath; }
          // the returned path will interpolate lng, ns if provided like giving a static path
          loadPath: '/locales/{{lng}}/{{ns}}.json',
        },

        load: 'currentOnly',
        debug: false,

        interpolation: {
          escapeValue: false, // not needed for react as it escapes by default
        },

        // special options for react-i18next
        // learn more: https://react.i18next.com/components/i18next-instance
        react: {
          wait: true,
        },
      },
      callback
    );

export default i18nInit();

是否可以在此处添加从数据库中获取语言值的功能,如果未设置,则返回到浏览器的语言环境?

【问题讨论】:

  • 我也对是否可以在数据库中获取语言环境翻译感兴趣。手动维护语言环境文件夹中的翻译很混乱

标签: reactjs locale i18next


【解决方案1】:

i18next-browser-languageDetector检测用户的浏览器语言,可能与DB中存储的值不同。

您可以对服务器进行 Api 调用以获取用户语言,如果未设置,请使用 i18next-browser-languageDetector 作为后备。

所以代码应该是这样的

export const i18nInit = async (callback = () => { }) => {
  const {lang} = await axios.get('/user-lang');

  const i18nConfig = i18n
    .use(Backend)
    .use(reactI18nextModule);

  if(!lang) {
    i18nConfig.use(LanguageDetector);
  }

  i18nConfig.init({
    lng: lang || undefined // if it has value, it will use this lang, if not, it is undefined as a default value of `lng`
    ...
  });
}

如果你想“花哨”,你可以编写一个自定义异步语言检测器,如下所示:

module.exports = exports = function(fallback){
  return {
    type: 'languageDetector',
    async: true,
    init: () => {},
    detect: async function(callback){
      try {
        await axios.get('user-lang')
          .then(language => {
            if(language){
              return callback(language)
            }

            return callback();
          })
      } catch(error){
        callback();
      }

    },
    cacheUserLanguage: function(language){
      // ... cache users lang
    }
  }
};

基于i18next-react-native-async-storage

【讨论】:

    【解决方案2】:

    我目前正在尝试将语言检测器选项设置为:

    const options = {
      order: ['localStorage', 'navigator'],
    
      lookupLocalStorage: 'i18nextLng',
    }
    

    所以我可以先调用axios,然后在localStorage 中设置值。如果该值未在localStorage 中设置,则应查看navigator。如果有人有更好的答案,我会将您的答案标记为已接受,稍后我会在此答案有效时更新此答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-10
      • 2019-04-24
      • 2020-01-24
      • 1970-01-01
      • 2018-03-29
      • 1970-01-01
      • 2019-12-31
      相关资源
      最近更新 更多