我正在尝试将一个使用Redux
的Container
与HOC
包装在一起,它也使用Redux
,将我带到以下错误:
TypeError: Object(...) is not a function
> 112 | export default connect(mapStateToProps, mapDispatchToProps) (withRouter(withError(VeggieBuilder)))
我一直在尝试自己弄清楚,我想该解决方案与导出HOC
或Container
时使用redux
compose
有关。
我将在此处发布整个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)
现在我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
将返回一个函数,该函数需要 react 组件作为参数。
因此,当您使用export default connect(mapStateToProps, mapActionsToProps)(withError)
请注意withError
不是 react 组件,而是一个返回 react 组件的函数。