我们一直在使用react、react router和redux。现在我们想要添加injectIntl。我的语法有点问题,希望你能帮我。
import React, { Fragment } from 'react';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { intlShape, injectIntl } from 'react-intl';
...
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(MyComponent));
我把它改成了
export default injectIntl(withRouter(connect(mapStateToProps, mapDispatchToProps)(MyComponent)));
错误是
警告:函数作为React子级无效。如果您返回组件而不是从render返回组件,则可能会发生这种情况。或者你想调用这个函数而不是返回它。
我需要做什么来组合所有这些框架?
发布于 2018-06-06 06:45:46
它看起来injectIntl
没有提升/复制包装组件的静态,这很可能是问题的原因。
Reacts说Static Methods Must Be Copied Over:
但是,当您将HOC应用于组件时,原始组件是用容器组件包装的。这意味着新组件没有原始组件的任何静态方法。
您可以在injectIntl
追踪器中查看already reported issue。
有一个变通的,而修复是正式应用于项目的。
您可以创建一个injectIntl
的包装器,它正确地复制了statics:
// utils/injectIntl.js
import { injectIntl as baseInjectIntl } from 'react-intl';
import hoistNonReactStatic from 'hoist-non-react-statics';
/**
* A fixed injectIntl that hoists statics.
*/
export function injectIntl(WrappedComponent: Function): Function {
const WrapperComponent = baseInjectIntl(WrappedComponent);
hoistNonReactStatic(WrapperComponent, WrappedComponent);
return WrapperComponent;
}
然后在你的应用中使用它,如下所示:
import injectIntl from 'utils/injectIntl'
// ...
injectIntl(withRouter(connect(mapStateToProps, mapDispatchToProps)(MyComponent)));
发布于 2018-06-06 16:42:43
在使用injectIntl
之前,你应该首先用<IntlProvider>
包装你的根/应用组件。
ReactDOM.render(
<IntlProvider
locale={usersLocale}
messages={translationsForUsersLocale}
>
<App/>
</IntlProvider>,
document.getElementById('container')
);
下面是react-intl
docs所说的:
创建I18n Context
React Intl使用提供者模式将i18n上下文的范围限定为组件树。这允许在组件树的根部提供诸如当前区域设置和一组已翻译的字符串/消息之类的配置,并使其可用于<Formatted*>
组件。这与像Redux这样的Flux框架用来在组件树中提供对存储的访问的概念是相同的。
使用React <IntlProvider>
的所有应用程序都必须使用 Intl组件。
最常见的用法是用<IntlProvider>
包装根React组件,并使用用户的当前语言环境和相应的翻译后的字符串/消息对其进行配置
https://stackoverflow.com/questions/50709602
复制相似问题