我遇到了同样的问题,这就是我发现的:
为了更改语言,我使用了here 提供的解决方案,它基本上是通过 Connect 函数将 IntlProvider 绑定到 ReduxStore。另外不要忘记在语言更改时包含重新渲染组件的键。这基本上是所有代码:
这是ConnectedIntlProvider.js,只是绑定了默认的IntlProvider(注意github原始评论中缺少的key prop)
import { connect } from 'react-redux';
import { IntlProvider } from 'react-intl';
// This function will map the current redux state to the props for the component that it is "connected" to.
// When the state of the redux store changes, this function will be called, if the props that come out of
// this function are different, then the component that is wrapped is re-rendered.
function mapStateToProps(state) {
const { lang, messages } = state.locales;
return { locale: lang, key: lang, messages };
}
export default connect(mapStateToProps)(IntlProvider);
然后在你的入口点文件中:
// index.js (your top-level file)
import ConnectedIntlProvider from 'ConnectedIntlProvider';
const store = applyMiddleware(thunkMiddleware)(createStore)(reducers);
ReactDOM.render((
<Provider store={store}>
<ConnectedIntlProvider>
<Router history={createHistory()}>{routes}</Router>
</ConnectedIntlProvider>
</Provider>
), document.getElementById( APP_DOM_CONTAINER ));
接下来要做的就是实现 reducer 来管理语言环境,并让动作创建者按需更改语言。
至于存储翻译的最佳方式 - 我发现很多关于这个主题的讨论和情况似乎很混乱,老实说,我很困惑 react-intl 的制造商如此关注日期和数字格式而忘记了翻译.所以,我不知道绝对正确的处理方法,但这就是我所做的:
创建文件夹“locales”并在其中创建一堆文件,如“en.js”、“fi.js”、“ru.js”等。基本上所有您使用的语言。
在每个文件中导出 json 对象,翻译如下:
export const ENGLISH_STATE = {
lang: 'en',
messages: {
'app.header.title': 'Awesome site',
'app.header.subtitle': 'check it out',
'app.header.about': 'About',
'app.header.services': 'services',
'app.header.shipping': 'Shipping & Payment',
}
}
其他文件具有完全相同的结构,但内部包含已翻译的字符串。
然后在负责语言更改的 reducer 中,从这些文件中导入所有状态,并在调度更改语言的操作后立即将它们加载到 redux 存储中。您在上一步中创建的组件会将更改传播到 IntlProvider 并且将发生新的语言环境。使用 <FormattedMessage> 或 intl.formatMessage({id: 'app.header.title'})} 在页面上输出它,在他们的 github wiki 上阅读更多信息。
他们那里有一些DefineMessages功能,但老实说我找不到任何好的信息如何使用它,基本上你可以忘记它并没问题。