简体   繁体   中英

Extending react component received by redux connect()

Is it somehow possible to extend component that is being connected by Redux connect() function? For example, if I am inside form-container.js and I'm using

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

Is there a way to override some methods like this:

FormContainer.componentDidMount = () => ...

Or add custom functions?

You can use High order components for this. I'm borrowing this example from 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} />
    }
  }
}

How to use this custom method:

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)

As far as I know, you cannot override life-cycle methods of a React component. But you can inject methods by using HoC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM