2016-12-06 92 views
1

是否有可能通過Redux connect()函數擴展正在連接的組件?例如,如果我是裏面form-container.js和我使用通過redux connect擴展反應組件()

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

有沒有一種方法來覆蓋一些方法是這樣的:

FormContainer.componentDidMount =() => ... 

或者添加自定義的功能呢?

回答

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) 

據我所知,你不能覆蓋一個陣營組件的生命週期方法。但是你可以使用HoC注入方法。