react-intl语言切换器不会更新孙子组件中的Formattedmessage

时间:2019-06-19 20:27:43

标签: reactjs state translation react-intl

所以我已经开始在较旧的react-project中使用react-intl(请不要判断)。

在index.js中,我将状态更改为所选语言:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import {
    BrowserRouter as Router, Route
} from 'react-router-dom';
import * as serviceWorker from './serviceWorker';

// Data
import Landing from "./components/landing/landing";
import Login from './components/app/auth/login/Login';
import Register from './components/app/auth/register/Register';
import intlEN from 'react-intl/locale-data/en';
import intlDE from 'react-intl/locale-data/de';

import { IntlProvider, addLocaleData } from "react-intl";
import messages_en from "./translations/en.json";
import messages_de from "./translations/de.json";

addLocaleData([...intlEN, ...intlDE]);

let i18nConfig = {
    locale: 'EN',
    messages: messages_en
};

// App
class Root extends Component {
    constructor(props) {
        super(props);
        this.state = { locale: "EN" }
        this.onChangeLanguage = this.onChangeLanguage.bind(this);
    }

    onChangeLanguage(lang) {
        switch (lang) {
            case 'DE': i18nConfig.messages = messages_de; break;
            case 'EN': i18nConfig.messages = messages_en; break;
            default: i18nConfig.messages = messages_en; break;
        }
        this.setState({ locale: lang });
        i18nConfig.locale = lang;
    }

    render() {
        return (
            <Router>
                <Route exact path="/" onChangeLanguage={this.onChangeLanguage} component={Landing} />
                <Route path="/login" onChangeLanguage={this.onChangeLanguage} component={Login} />
                <Route path="/register" render={() => <Register onChangeLanguage={this.onChangeLanguage} />} />
            </Router>
        )
    }
}


ReactDOM.render(
    <IntlProvider locale={i18nConfig.locale} key={i18nConfig.locale} messages={i18nConfig.messages}>
        <Root />
    </IntlProvider>,
    document.querySelector("#root")
)

因此,在“注册”组件中,我提供了具有更改语言功能的格式化消息:

import React, { Component, ProtoTypes } from 'react';
import {FormattedMessage, FormattedHTMLMessage} from 'react-intl';

class Register extends Component {
    render() {
        const { onChangeLanguage } = this.props

        return (
            <div className="container d-flex vh-100 flex-column">
                <button className="btn btn-link" onClick={(param) => onChangeLanguage('EN')}>
                    English
                </button>
                <button className="btn btn-link" onClick={(param) => onChangeLanguage('DE')}>
                    German
                </button>

                <FormattedMessage id="landing.hero.title"></FormattedMessage>
            </div>
        )
    }
}

export default Register

问题是,不幸的是,它没有更新任何内容,格式化后的消息仅在页面开始时返回了选定的消息。

0 个答案:

没有答案