react+redux使用static mapStoreToProps

以下是redux官网上使用的connect用法:

class Container extends React.Component{
    ...
}
const mapStateToProps = (state, ownProps) => {
    ...
}

const mapDispatchToProps = (dispatch, ownProps) => {
    ...
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Container)

我就不太喜欢这种表达方法,我的目标是将map方法放进Container中作为静态方法,直接使用Container就是connect后的组件。经过我的多番尝试,最终使用Decorator实现:

function connection(target){
  return connect(target.mapStoreToProps , target.mapDispatchToProps)(target);
}

@connection
class Container extends React.Component{
    ...
    static mapStateToProps(state , ownProps){
        ...
    }
    static mapDispatchToProps (state , ownProps){
        ...
    }
}

export default Container ;

经过Decorator修饰的Container就可以使用redux中的数据了。

posted @ 2017-03-23 23:08  linyongkangm  阅读(472)  评论(0)    收藏  举报