[英]How to use a connected-to-Redux-Higher-Order-Component inside a Component which is also connected to Redux
我正在嘗試包裝一個使用Redux
和HOC
的Container
,它也使用Redux
,導致出現以下錯誤:
TypeError: Object(...) is not a function
> 112 | export default connect(mapStateToProps, mapDispatchToProps) (withRouter(withError(VeggieBuilder)))
我一直在嘗試自己解決這個問題,我猜這個解決方案與在導出我的HOC
或我的Container
時使用來自redux
的compose
有關。
我將在此處發布整個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)
現在我Container
的export
部分稱為VeggieBuilder
export default connect(mapStateToProps, mapDispatchToProps) (withRouter(withError(VeggieBuilder)))
如果在我的HOC
export
時刪除與Redux
的connection
,錯誤就會消失。
在此先感謝大家。
如果此處需要任何其他信息,我將相應地編輯問題。
您可以這樣修改您的 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;
使用mapState
和mapDispatch
調用connect
將返回一個 function,它需要一個 React 組件作為參數。
因此,當您使用export default connect(mapStateToProps, mapActionsToProps)(withError)
,請注意withError
不是反應組件,而是返回反應組件的 function。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.