首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从数据库获取区域设置,而不是浏览器i18next

从数据库获取区域设置,而不是浏览器i18next
EN

Stack Overflow用户
提问于 2020-01-24 16:35:15
回答 2查看 1.7K关注 0票数 4

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

代码语言:javascript
复制
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();

是否可以在这里添加一个从数据库获取语言值的功能,如果没有设置,它将返回到浏览器的区域设置?

EN

回答 2

Stack Overflow用户

发布于 2020-01-24 16:53:49

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

您可以向服务器发出Api调用以获取用户lang,如果未设置,则使用i18next-browser-languageDetector作为备用。

因此,代码应该如下所示

代码语言:javascript
复制
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`
    ...
  });
}

如果你想变得“花哨”,你可以编写一个自定义的异步语言检测器,就像这样:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2020-01-24 16:46:39

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

代码语言:javascript
复制
const options = {
  order: ['localStorage', 'navigator'],

  lookupLocalStorage: 'i18nextLng',
}

因此,我可以先调用axios,然后在localStorage中设置值。如果该值未在localStorage中设置,则应在navigator中查找。如果有人有更好的答案,我会将你的答案标记为被接受的答案,稍后当它生效时,我会更新这个答案。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59892851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档