是否有可能扩展由Redux connect()
函数连接的组件?例如,如果我在form-container.js
内部,并且正在使用
const FormContainer = connect(
mapStateToProps,
mapDispatchToProps
)(Form)
是否有一种方法可以覆盖这样的方法:
FormContainer.componentDidMount = () => ...
还是添加自定义函数?
发布于 2016-12-06 03:42:47
您可以为此使用高阶组件。我从这篇文章借用这个例子
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注入方法。
https://stackoverflow.com/questions/40994351
复制