扩展redux connect()接收的反应组件

时间:2016-12-06 11:32:37

标签: javascript reactjs redux react-redux

是否有可能扩展Redux connect()函数连接的组件?例如,如果我在form-container.js内并且我正在使用

const FormContainer = connect(
    mapStateToProps,
    mapDispatchToProps
)(Form)

有没有办法覆盖这样的方法:

FormContainer.componentDidMount = () => ...

或添加自定义功能?

1 个答案:

答案 0 :(得分:0)

您可以使用高阶组件。我从this article

借用了这个例子
function HigherOrderComponent(WrappedComponent) {
  return class NewComponent extends React.Component {
    constructor() {
      super(props)
      this.customMethod = this.customMethod.bind(this)
    }
    customMethod() {
      console.log('You called an injected method');
    }
    render() {
      return <WrappedComponent {...this.props} customMethod={this.customMethod} />
    }
  }
}

如何使用此自定义方法:

import HigherOrderComponent from './HigherOrderComponent'

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
  }
  componentDidMount() {
    this.props.customMethod()
  }
  render() {
      ...
  }
}
const MutatedComponent = HigherOrderComponent(MyComponent)
const ConnectedComponent = connect(
  mapStateToProps,
  mapDispatchToProps
)(MutatedComponent)

据我所知,你不能覆盖React组件的生命周期方法。但是你可以使用HoC注入方法。