【问题标题】:Dynamically import language json file for react / react-intl为 react/react-intl 动态导入语言 json 文件
【发布时间】:2017-10-10 08:42:31
【问题描述】:

这是我配置客户端以通过 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 文件。

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

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

谢谢

【问题讨论】:

    标签: javascript json reactjs react-intl babel-plugin-react-intl


    【解决方案1】:

    通过以下代码解决了。将它们张贴在这里以防有人需要。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-18
      • 2017-05-08
      • 2020-10-18
      • 2020-03-02
      • 2018-06-24
      • 1970-01-01
      • 2021-08-13
      • 2020-07-06
      相关资源
      最近更新 更多