下面是高阶组件。HOC 专门连接到 redux 以访问动作创建者之一:importantReduxAction
.
function withExtraStuff (InnerComponent) {
return class Enhancer extends React.Component {
constructor(props){
super(props)
this.importantMethod = this.importantMethod.bind(this)
}
importantMethod(){
//try to call the higher order component's action creator
this.props.importantReduxAction()
}
render(){
return <InnerComponent
{...this.props}
importantMethod={this.importantMethod}
/>
}
}
let mapDispatchToProps = (dispatch)=>{
return bindActionCreators({importantReduxAction}, dispatch)
}
return connect(null, mapDispatchToProps, null, {pure: false})(Enhancer)
}
这是将使用 HOC 组件的包装组件。它还将自己连接到 redux 以获得对不同方法的访问权限:otherReduxAction
.
class ChildComponent extends React.Component {
constructor(props){
super(props)
this.doImportantThing = this.doImportantThing.bind(this)
}
doImportantThing(){
//try to call the higher order component's method (this is where problems occur)
this.props.importantMethod()
//do something with this components dispatch
this.props.otherReduxAction()
}
render(){
return <div>
{this.doImportantThing()}
</div>
}
}
let EnhancedComponent = withExtraStuff(ChildComponent)
let mapDispatchToProps = (dispatch)=>{
return bindActionCreators({otherReduxAction}, dispatch)
}
export default connect(null, mapDispatchToProps, null, {pure: false})(EnhancedComponent)
问题发生mapDispatchToProps
在我的 HOC 内部被孩子覆盖,并且动作创建者:importantReduxAction
,永远不会被传递到我的 HOC 中。它收到以下错误:
方法未定义
我已经通过将方法传递给我的子组件来解决这个问题,如下所示:
/* CHILD COMPONENT DEFINITION ABOVE */
let mapDispatchToProps = (dispatch)=>{
return bindActionCreators({otherReduxAction, importantReduxAction}, dispatch)
}
但这个解决方案并不是我真正想要的工作方式。有没有办法让我的 HOC 合并到它想要与包装组件的动作创建者一起使用的动作创建者中?还是我必须找到解决这个问题的新方法?
TLDR:使用动作创建者的 HOC 组件包装了也有一个的子组件。HOC 动作创建者被踢到遏制并且从未通过。