通过redux connect扩展反应组件()

问题描述:

是否有可能通过Redux connect()函数扩展正在连接的组件?例如,如果我是里面form-container.js和我使用通过redux connect扩展反应组件()

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) 

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