Dynamically import language json file for react / react-intl

核能气质少年 提交于 2019-12-21 13:08:10

问题


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));

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.

Thanks


回答1:


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];


来源:https://stackoverflow.com/questions/43913832/dynamically-import-language-json-file-for-react-react-intl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!