首页 > 解决方案 > 如何在也连接到 Redux 的 Component 中使用 connected-to-Redux-Higher-Order-Component

问题描述

我正在尝试将使用的 a 与也使用的 a 包装起来Container,从而Redux导致以下错误:HOCRedux

TypeError: Object(...) is not a function
> 112 | export default connect(mapStateToProps, mapDispatchToProps) (withRouter(withError(VeggieBuilder)))

我一直试图自己解决这个问题,我猜该解决方案与compose导出reduxmyHOC或 my Container.

HOC我将在此处发布整个内容,以及块container's下方的导出部分HOC

import React, {Fragment} from "react";
import Modal from "../../UI/Modal/Modal";
import { connect } from 'react-redux'
import * as actionCreators from  '../../../store/actions/indexActions'

const withError = WrappedComponent => {
    return props => {
        return<Fragment>
            <Modal show={props.error} modalCanceled={() => props.onResetError()}>
                {props.error && props.error}
            </Modal>
            <WrappedComponent {...props} />
        </Fragment>
    }
}

const mapStateToProps = state => {
    return {
        error: state.httpReqReducer.errorMessage
    }
}

const mapActionsToProps = dispatch => {
    return {
        onResetError: () => dispatch(actionCreators.resetError())
    }
}

export default connect(mapStateToProps, mapActionsToProps)(withError)

现在exportContainer叫的部分VeggieBuilder

export default connect(mapStateToProps, mapDispatchToProps) (withRouter(withError(VeggieBuilder)))

如果删除我connection的错误消失ReduxexportHOC

在此先感谢大家。

如果此处需要任何其他信息,我将相应地编辑问题。

标签: reactjsreduxreact-redux

解决方案


你可以这样修改你的 HOC:

import React, { Fragment } from "react";
import Modal from "../../UI/Modal/Modal";
import { connect } from 'react-redux'
import * as actionCreators from '../../../store/actions/indexActions'

const withError = WrappedComponent => {
  const wrappedComp = props => {
    return <Fragment>
      <Modal show={props.error} modalCanceled={() => props.onResetError()}>
        {props.error && props.error}
      </Modal>
      <WrappedComponent {...props} />
    </Fragment>
  }

  const mapStateToProps = state => {
    return {
      error: state.httpReqReducer.errorMessage
    }
  }

  const mapActionsToProps = dispatch => {
    return {
      onResetError: () => dispatch(actionCreators.resetError())
    }
  }

  return connect(mapStateToProps, mapActionsToProps)(wrappedComp);
}

export default withError;

调用and将返回一个函数connect,该函数需要一个反应组件作为参数。mapStatemapDispatch

因此,当您使用export default connect(mapStateToProps, mapActionsToProps)(withError)note 时,withError它​​不是一个反应组件,而是一个返回反应组件的函数。


推荐阅读