请考虑React Native代码:
MyForm.js
Class MyForm extends Component{
render(){
//Code Left out for simplicity
}
}
function mapStateToProps(){//code left out for simplicity}
MyForm.propTypes = {//code left out for simplicity};
export default(connect(mapStateToProps, Actions)(withHocComponent(MyForm)));
HoComponent.js
export default withHocComponent = WrappedComponent => class HoComponent extends Component {
class HocComponent extends Component{
render(){
<View>
<WrappedComponent/>
</View>
}
}
}
function mapStateToProps(state) {
return {
prop1: state.myReducer.someProp,
};
}
export default connect(mapStateToProps)(withHocComponent);
但是,我收到以下错误:
无法将类作为函数调用。
堆栈指的是这一行:export default(connect(mapStateToProps, Actions)(withHocComponent(MyForm)));
我正在尝试在redux connect
函数之外实现额外的高阶组件。
答案 0 :(得分:2)
好的,所以我希望这就是你要找的东西。如果您有任何问题随时问。
<强> HOC 强>
function withHocComponent(WrappedComponent) {
class Wrapper extends Component {
render() {
// here you could pass props to your wrappedComponent
return <WrappedComponent />;
}
const mapStateToProps = (state) => {
//code left out for simplicity
}
//connect your HOC to the store inside the Wrapper
return connect(mapStateToProps, {})(Wrapper);
}
}
export default withHocComponent;
<强> MyForm的强>
Class MyForm extends Component{
render(){
//Code Left out for simplicity
}
}
function mapStateToProps(){//code left out for simplicity}
MyForm.propTypes = {//code left out for simplicity};
// Here is the part where the magic happens.
// Pass your HOC your connected component
export default withHocComponent(connect(mapStateToProps, {})(MyForm));
答案 1 :(得分:0)
感谢@TimH, 我通过将类mapStateToProps和mapDispatchToProps放入HOC中进行了一些更改,当它们位于HOCComponent中时,我无法使其正常工作。
const HOC = (WrappedComponent) => {
class HOCComponent extends Component {
constructor(props) {
super(props);
this.state = {
talking: false
};
}
render() {
return (<WrappedComponent speak={this.speak} />);
}
}
const mapStateToProps = state => ({
start: state.lessonStartReducer.start,
});
const mapDispatchToProps = dispatch => ({
startLesson: (payload) => {
dispatch(startLesson(payload));
},
});
return connect(
mapStateToProps,
mapDispatchToProps
)(HOCComponent);
}
export default HOC;