【发布时间】:2019-01-18 23:25:24
【问题描述】:
我想创建一个 HOC,它允许我调用从后端获取数据并在加载时显示加载器掩码的方法。诀窍是我希望能够为不同的组件传递不同的操作。
所以我想这样称呼它:
export default withPage({
getLoadingStatus: getStatus,
actionOnLoad: booksActions.getAllBooksRequest
})(ShareABookContainer);
当我在那里传递一些道具时,我定义了我的 withPage.js,如下所示:
const withPage = ({
actionOnLoad,
getLoadingStatus
}) => WrappedComponent => () => {
return (
<PageContainer
getLoadingStatus={getLoadingStatus}
wrappedComponent={WrappedComponent}
actionOnLoad={actionOnLoad}
/>
);
};
export default withPage;
PageContainer.js 是最常见的容器,所以:
const PageContainer = props => <PageComponent {...props} />;
const mapStateToProps = (state, ownProps) => ({
...
});
const mapDispatchToProps = (dispatch, ownProps) => {
...
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(PageContainer);
PageComponent 也是一个普通的 Component:
class PageComponent extends Component {
componentDidMount() {
...
}
render() { return <this.props.wrappedComponent />;
}
}
export default PageComponent;
发生的情况是没有渲染任何内容,如果我收到 console.log WrappedComponent:
WrappedComponent ƒ a(e,t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,a);var r=function(e,t){if(!e)throw new ReferenceError("this has not been 初始化 - super()…
当我传递一些 div 时,例如测试而不是一切正常,但我需要的是渲染传递的组件。
我不知道我做错了什么,互联网上的例子也没有帮助。我无法找到像我这样的情况的示例(因此将道具传递给 HOC 并在那里使用 Redux,要么是一个,要么是另一个)。对于任何想法/建议/答案,我将不胜感激。
【问题讨论】:
-
我不确定,但我认为您的 hoc 定义应该更像这样: const withPage = ({ actionOnLoad, getLoadingStatus }) => WrappedComponent =>
所以没有最后一个空箭头函数。 -
@MaciejWojsław 感谢您的建议,但它不起作用。如果没有最后一个空箭头函数,我会得到
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
标签: javascript reactjs redux react-redux