嗨,
我有一个呈现页面的组件(Home.jsx),它使用名为 withLocalized (react-localize-redux)的包来处理语言翻译。
现在我要做的是将处理语言初始化的代码分离为HOC,以便我可以在其他组件中再次使用该逻辑。
新的HOC位于名为 Localize.js
的单独文件中问题是Home.jsx使用connect,当我尝试用withLocalize(也是HOC)包装新的HOC(Localize)时,我得到:
TypeError:当我尝试使用Connect HOC包装React HOC时,无法将类作为函数调用。
如果我将 withLocalize 导入到Home.jsx组件中,我设法解决了这个问题,但是如果我理解正确,我希望Localize.js文件将包含所有逻辑与语言设置有关。
这是Home.jsx组件:
import React, { Component } from 'react';
import Footer from 'components/Footer/V2/Footer';
import { connect } from 'react-redux';
import * as actions from '../../store/actions/auth';
import { Localize } from 'texts/localize';
import { withLocalize } from 'react-localize-redux';
class Home extends Component {
constructor(props) {
super(props);
}
render() {
return <Footer />
}
}
const mapStateToProps = state => {
return {
x: state.x,
y: state.y,
lang: state.lang
};
};
const mapDispatchToProps = dispatch => {
return {
onTest: (x, y) => dispatch(actions.authIp(x, y)),
};
};
export default connect(mapStateToProps,
mapDispatchToProps)(withLocalize(Localize(Home)));
这是 localize.js 中的Localize HOC:
import React, { Component } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import * as trans from '@trans/index';
export const Localize = WrappedComponent => {
return class Localize extends Component {
constructor(props) {
super(props);
const init = {
languages: [
{ name: 'English', code: 'en' },
{ name: 'Chinese', code: 'cn' },
{ name: 'Korean', code: 'kr' }
],
options: {
renderToStaticMarkup,
renderInnerHtml: true,
defaultLanguage: 'en'
}
};
this.props.initialize({
languages: init.languages,
options: init.options
});
this.props.addTranslationForLanguage(trans.en, 'en');
this.props.addTranslationForLanguage(trans.cn, 'cn');
this.props.addTranslationForLanguage(trans.kr, 'kr');
}
componentDidMount() {
this.props.setActiveLanguage(this.props.lang);
}
render() {
return <WrappedComponent {...this.props} />;
}
};
};
export default Localize;
此组件处理翻译,我要做的是使 withLocalize 包裹ppHOC,然后进行加工
我在做什么错? 我希望Localize组件包含与语言有关的所有逻辑,并且导出将类似于
export default connect(mapStateToProps,
mapDispatchToProps)(Localize(Home));
代替:
export default connect(mapStateToProps,
mapDispatchToProps)(withLocalize(Localize(Home)));