react-intl与redux语言swicher

时间:2017-12-28 15:40:47

标签: reactjs redux react-intl

我试图使用react-inlt和redux创建语言切换器,但是当我尝试切换时,则不会呈现视图(< FormattedMessage> dosen&t; tt change),但redux工作和<中的区域设置IntlProvider>改变了。我在Chrome控制台中没有任何错误。

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux'; 
import { Provider } from 'react-redux';
import thunk from 'redux-thunk'; 
import { addLocaleData } from 'react-intl';
import en from "react-intl/locale-data/en";
import pl from "react-intl/locale-data/pl";
import App from './App';
import { localeSet } from './actions/locale';
import rootReducer from './rootReducer';
...
...
addLocaleData([...en, ...pl]);
...

App.js

import React from 'react';
import { connect } from 'react-redux';
import { Route } from 'react-router-dom';
import { IntlProvider } from 'react-intl';
import messages from "./messages";
...

class App extends React.Component {

  render() {
    const { lang } = this.props;
    return (
      <IntlProvider locale={lang} messages={messages[lang]}>
        <div className="ui container">
          <TopNavigation />
        </div> 
      </IntlProvider>
    );
  }
}

function mapStateToProps(state) {
  return {
    lang: state.locale.lang
  }
}

export default connect(mapStateToProps)(App);

TopNavigation.js

import { FormattedMessage } from 'react-intl';
import { setLocale } from '../../actions/locale';
...

class TopNavigation extends React.Component {

    render() {

        return (

          <FormattedMessage id="nav.dashboard" defaultMessage="Dashboard" />

           <a role="button" onClick={() => this.props.setLocale("en")}>
             EN
           </a>{" "}
           |
           <a role="button" onClick={() => this.props.setLocale("pl")}>
             PL
           </a>

        );
    }
}

export default connect(null, { setLocale })(TopNavigation);

messages.js

export default {
    en: {
        'nav.dashboard' : "Dashboard"
    },
    pl: {
        'nav.dashboard' : "Panel Administracyjny"        
    }
}

动作/ locale.js

import { LOCALE_SET } from "../types";

export const localeSet = lang => ({
  type: LOCALE_SET,
  lang
});

export const setLocale = lang => dispatch => {
  localStorage.alhubLang = lang;
  dispatch(localeSet(lang));
};

减速器/ locale.js

import { LOCALE_SET } from "../types";

export default function locale(state ={ lang: "pl"}, action = {}) {
    switch(action.type) {
        case LOCALE_SET:
            return { lang: action.lang };
        default: 
            return state;
    }
}

types.js

export const LOCALE_SET = "LOCALE_SET";

0 个答案:

没有答案