扩展 redux connect() 接收到的 react 组件

Extending react component received by redux connect()

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

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

有没有办法覆盖像这样的一些方法:

FormContainer.componentDidMount = () => ...

或者添加自定义功能?

您可以为此使用高阶组件。我从 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 注入方法。