我正在尝试为表示组件创建一个HOC组件,并且在语法方面遇到一些麻烦。
假设我的演示组件名为BlogViewerBase
,让我们调用HOC组件BlogViewerHoc
。我想要以下内容:
这段代码看起来不错吗?
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 :(得分: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));
答案 1 :(得分:0)
您的代码对我来说似乎没问题:)
为了简化阅读,我会做以下调整(但这只是我的观点):
const connector = connect(mapStateToProps, mapDispatchToProps)
...
export default function hocBlogViewer(BlogViewerBase) {
return connector(
class BlogViewerHoc extends React.Component {
...