簡體   English   中英

如何在也連接到 Redux 的組件中使用連接到 Redux-Higher-Order-Component

[英]How to use a connected-to-Redux-Higher-Order-Component inside a Component which is also connected to Redux

我正在嘗試包裝一個使用ReduxHOCContainer ,它也使用Redux ,導致出現以下錯誤:

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

我一直在嘗試自己解決這個問題,我猜這個解決方案與在導出我的HOC或我的Container時使用來自reduxcompose有關。

我將在此處發布整個HOC ,並僅在HOC塊下方發布container's導出部分。

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)

現在我Containerexport部分稱為VeggieBuilder

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

如果在我的HOC export時刪除與Reduxconnection ,錯誤就會消失。

在此先感謝大家。

如果此處需要任何其他信息,我將相應地編輯問題。

您可以這樣修改您的 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;

使用mapStatemapDispatch調用connect將返回一個 function,它需要一個 React 組件作為參數。

因此,當您使用export default connect(mapStateToProps, mapActionsToProps)(withError) ,請注意withError不是反應組件,而是返回反應組件的 function。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM