高阶组件redux调度被包装组件redux调度覆盖

Jam*_*ick 7 reactjs redux react-redux es6-class higher-order-components

以下是高阶组件.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)
}
Run Code Online (Sandbox Code Playgroud)

这是将使用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)
Run Code Online (Sandbox Code Playgroud)

问题出现mapDispatchToProps在我的HOC内部被孩子覆盖,并且动作创建者:importantReduxAction永远不会被传递到我的HOC中.它收到的错误是:

方法未定义

我通过将方法传递到我的子组件中解决了这个问题:

/* CHILD COMPONENT DEFINITION ABOVE */

let mapDispatchToProps = (dispatch)=>{
  return bindActionCreators({otherReduxAction, importantReduxAction}, dispatch)
}
Run Code Online (Sandbox Code Playgroud)

但是,这个解决方案并不是我想让事情发挥作用的方式.有没有办法让我的HOC合并到它想要与包装组件使用的动作创建器中?或者我是否必须找到一个新方法?

TLDR: HOC使用动作创建者的组件包装也具有动作创建者的子组件.HOC行动创造者被踢遏制并且从未通过.

Luk*_*uke 3

看来你的例子有问题。

function withExtraStuff (InnerComponent) {
  return class Enhancer extends React.Component {/* ... */}

  // ...

  return connect(/* ... */)(Enhancer)
}
Run Code Online (Sandbox Code Playgroud)

你return从 HOC 中 ing 了两次,所以你的Enhancer从未被connect编辑过。

这只是您的示例中的拼写错误吗?或者您的代码中是否存在同样的问题?因为这确实会导致您所看到的问题。