动态导入语言json文件以进行react/react-intl [英] Dynamically import language json file for react / react-intl

查看:376
本文介绍了动态导入语言json文件以进行react/react-intl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我配置客户端以通过react-intl呈现正确语言的方式.

This is the way I configure my client to render the proper language through react-intl.

import localeData from './translations/en.json';
//import localeData from './translations/xx.json';  <-- any language

const render = routes => {
  match({ history, routes }, (error, redirectLocation, renderProps) => {
    ReactDOM.render(
      <HotEnabler>
        <IntlProvider locale={locale} messages={localeData}>
          <Provider store={store} app={app} restApp={restApp} key="provider">
            <Router {...renderProps} render={renderRouter} history={history}>
              {routes}
            </Router>
          </Provider>
        </IntlProvider>
      </HotEnabler>,
      dest
    );
  });
};

render(getRoutes(store));

但是我想基于cookie中的语言环境动态导入localeData.因此,如果用户的语言环境为"en",则我只会加载en.json文件.

However I would like to import the localeData dynamically based on the locale within a cookie. So if the locale of my user is "en", I will only load in the en.json file.

const locale = Cookie.get('locale') || 'en';

const render = routes => {
  match({ history, routes }, (error, redirectLocation, renderProps) => {
    ReactDOM.render(
      <HotEnabler>
        <IntlProvider locale={locale} messages={localeData}>
          <Provider store={store} app={app} restApp={restApp} key="provider">
            <Router {...renderProps} render={renderRouter} history={history}>
              {routes}
            </Router>
          </Provider>
        </IntlProvider>
      </HotEnabler>,
      dest
    );
  });
};

render(getRoutes(store));

这样做的正确方法是什么?试图创建一个函数,但我无法将数据正确传递给消息.

What would be the proper way of doing this? Tried creating a function but I can't pass the data properly to messages.

谢谢

推荐答案

通过以下代码解决了它.将其张贴在此处,以防有人需要.

Got it solved through the following codes. Post them here in case someone needs it.

const languages = {
  en: require('./translations/en.json'),
  zn: require('./translations/zn.json')
};
const localeData = languages[locale];

这篇关于动态导入语言json文件以进行react/react-intl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆