在React JS(Redux)上设置默认语言

时间:2019-03-11 18:52:18

标签: javascript reactjs redux react-redux flux

我正在尝试为我的react redux应用程序设置一种默认的'en'语言,现在我在商店中插入了该语言,但是我想在lang文件夹中使用en.json文件,然后进行切换语言之间。

ConfigStore.js

import { ReduceStore } from 'flux/utils';
import ActionTypes from '../constants/AppConstants';
import AppDispatcher from '../dispatcher/AppDispatcher';
import config from '../../config';


class ConfigStore extends ReduceStore {

    getInitialState() {
        return {
            language: 'en',
            languageLabels: {}
        };
    }

    reduce(state, action) {
        switch (action.type) {
            case ActionTypes.LANGUAGE_REQUEST:
                var newState = Object.assign({}, state);
                newState.languageLabels = action.data;
                return newState;
            default:
                return state;
        }
    }
}

export default new ConfigStore(AppDispatcher);

App.js

    import React from "react";
    import { render } from "react-dom";
    import { BrowserRouter as Router, Route } from "react-router-dom";
    import Main from "./components/Main";
    import ErrorBoundary from "./components/ErrorBoundary";

    render(
        <Router>
            <ErrorBoundary>
                <div>
                    <Route path="/" component={ Main }/>
                </div>
            </ErrorBoundary>
        </Router>,
        document.getElementById("root")
    );

config.js

这是我具有默认设置的文件

const config = {
ServiceConfig: {
    url: 'http://192.168.30.145',
    port: '4000',
    ip: '127.0.0.1'
},

AppConfig: {
    appID: 'wsTrader',
    appName: 42,
    isManager: 0,
    key: '!@#TempKey',
    phoneLine: '0'
},

SiteConfig: {
    defaultLanguage: 'en'
}
};

module.exports = config;

1 个答案:

答案 0 :(得分:0)

您可以使用名为helmet的软件包来处理此问题:

import { Helmet } from 'react-helmet';

然后在您的render方法中,您可以拥有类似这样的内容:

class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet htmlAttributes={{ lang: some.language.from.redux.store }}>
                <meta charSet="utf-8" />
                <title>My Title</title>
            </Helmet>
            ...
        </div>
    );
  }
};