2017-08-21 43 views
1

我正在尝试为演示组件创建一个HOC组件,并且在语法上有点麻烦。为React组件创建一个HOC

比方说,我的演示组件被称为BlogViewerBase,我们称之为HOC组件BlogViewerHoc。我想以下几点:

  1. 我想在我的特别组成部分,一些处理函数
  2. 我想HOC组件连接到我的终极版店,得到国家和它传递给基础元件

此代码是否正确?

import React, { Component, PropTypes } from 'react'; 
import { connect } from 'react-redux'; 
import { bindActionCreators } from 'redux'; 

// Actions 
import * as myActions from '../actions/myActions'; 

// Base component 
import BlowViewerBase from '../components/blogViewerBase'; 

function hocBlogViewer(BlogViewerBase) { 

    return class BlogViewerHoc extends React.Component { 

     handlerFunction1() { 

      // Some logic here 
     } 

     handlerFunction2() { 

      // Some logic here 
     } 

     render() { 

      return <BlogViewerBase {...this.props} /> 
     } 
    } 
} 

function mapStateToProps(state) { 

    return { 

     var1: state.module.variable1, 
     var2: state.module.variable2 
    }; 
} 

function mapDispatchToProps(dispatch) { 

    return { 
     actions: bindActionCreators(myActions, dispatch) 
    }; 
} 

export default connect(mapStateToProps, mapDispatchToProps)(BlogViewerHoc(BlogViewerBase)); 

当我挣扎是HOC组件的例子我已经遇到看起来更像功能,我想我形成矿山更像是一个组件,因此不知道如果我连接到存储正确的方法。不知道mapPropsToState,mapDispatchToState和处理函数是否在正确的位置。

+0

您是否忘记将道具传递给包装组件?'.I can not help you,因为我对redux知之甚少。 –

+0

是的,处理函数也会被传递。谢谢。 – Sam

回答

0

定义您的HOC,然后将您的表示组件传递给它。此外,你可以绑定一个动作创建者到你的道具mapDispatchToProps。喜欢的东西:

import React, { Component, PropTypes } from 'react'; 
import { connect } from 'react-redux'; 
import { myActionCreator } from 'yourPathToYourActions'; 

// Actions 
import * as myActions from '../actions/myActions'; 

// Base component 
import BlowViewerBase from '../components/blogViewerBase'; 

function hocBlogViewer(WrappedComponent) { 

    return class extends React.Component { 

     handlerFunction1() { 

      // Some logic here 
     } 

     handlerFunction2() { 

      // Some logic here 
     } 

     componentDidMount() { 
     // I can dispatch this action now 
     this.props.myActionInProps(); 
     } 

     render() { 

      return <WrappedComponent {...this.props} /> 
     } 
    } 
} 

function mapStateToProps(state) { 

    return { 

     var1: state.module.variable1, 
     var2: state.module.variable2 
    }; 
} 

function mapDispatchToProps(dispatch) { 

    return { 
     myActionInProps: dispatch(myActionCreator()) 
    }; 
} 

export default connect(mapStateToProps, mapDispatchToProps)(hocBlogViewer(BlowViewerBase)); 
0

您的代码似乎是确定我:)

也许对于阅读简单起见,我会做以下调整(不过这只是我的意见):

const connector = connect(mapStateToProps, mapDispatchToProps) 

... 

export default function hocBlogViewer(BlogViewerBase) { 

    return connector(
    class BlogViewerHoc extends React.Component { 
... 
相关问题