React-Intl更改语言不会更改翻译

时间:2020-03-26 10:22:11

标签: reactjs internationalization react-intl

我对React-Intl有一个小问题。

加载该应用程序后,翻译正常,但是当我更改语言时,i18nConfig会更改,但翻译不会更新。

我尝试了几种方法,但无法使其正常工作。

App.js:

let i18nConfig = {
  locale: navigator.language.split(/[-_]/)[0],
  messages: getMessagesFromLang(navigator.language.split(/[-_]/)[0])
};

function getMessagesFromLang(lang) {
  switch (lang) {
    case "fr":
      return locale_fr;
    case "en":
      return locale_en;
    default:
      return locale_en;
  }
}

function onChangeLanguage(lang) {
  switch (lang) {
    case "fr": i18nConfig.messages = locale_fr; break;
    case "en": i18nConfig.messages = locale_en; break;
    default: i18nConfig.messages = locale_en; break;
  }
  i18nConfig.locale = lang;
}

function getCurrentLang() {
  return i18nConfig.locale;
}

export default function App() {
  return (
    <IntlProvider key={i18nConfig.locale} locale={i18nConfig.locale} messages={i18nConfig.messages}>
      <Content onChangeLanguage={onChangeLanguage} getCurrentLang={getCurrentLang} />
    </IntlProvider>
  );
}

Content.js:

const options = [{ value: "en", label: "English" },{ value: "fr", label: "Français" }];    
export default class Content extends React.Component {
  state = {
    selectedOption: null
  };

  handleChange = selectedOption => {
    this.setState({ selectedOption }, () =>
      console.log(`Option selected:`, this.state.selectedOption)
    );

    this.props.onChangeLanguage(selectedOption.value);
  };

  render() {
    return (
        <span><FormattedMessage id="app.content.link.rules" defaultMessage="Rules" /></span>
        <Select value={this.state.selectedOption} onChange={this.handleChange} options={options} />
    );
  }

1 个答案:

答案 0 :(得分:0)

好的,因此基本上react并不知道该更改,我进行了一些更改,以便react知道更改的时间:

export default function App() {
  const [lang, setLang] = React.useState(i18nConfig.locale) // keeps state of lang in App
  function onChangeLanguage(lang) {
    setLang(lang) // changes the lang when selec value changes
  }
  return (
    <IntlProvider key={lang} locale={lang} messages={getMessagesFromLang(lang)}>
      /* note how props are changed in order to stay updated */
      <Content onChangeLanguage={onChangeLanguage} getCurrentLang={getCurrentLang} />
    </IntlProvider>
  );
}