如何在也连接到 Redux 的组件中使用连接到 Redux 的高阶组件



我正在尝试将一个使用ReduxContainerHOC包装在一起,它也使用Redux,将我带到以下错误:

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

我一直在尝试自己弄清楚,我想该解决方案与导出HOCContainer时使用reduxcompose有关。

我将在此处发布整个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)

现在我Containerexport部分叫做VeggieBuilder

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

如果在HOCexport上删除带有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将返回一个函数,该函数需要 react 组件作为参数。

因此,当您使用export default connect(mapStateToProps, mapActionsToProps)(withError)请注意withError不是 react 组件,而是一个返回 react 组件的函数。

最新更新