reactjs - TypeError:在尝试实现 HOC 时,Object(...) 不是函数
问题描述
我试图在这里和其他帖子中阅读接受的答案,但不能放弃弄清楚这是否对我有帮助。我觉得那里的情况有所不同。
我已经看过一些关于如何使用 HOC 的示例,看起来就像我一样。是不是因为我想用 HOC 来实现connect
?
这是我的 HOC:
import React from "react";
import { connect } from "react-redux";
const withResults = WrappedComponent => {
return class extends React.Component {
render() {
return <WrappedComponent {...this.props} />;
}
}
};
const mapStateToProps = state => {
return {
results: state.results
};
};
export default connect(mapStateToProps)(withResults);
这是我试图用 HOC 包装的组件:
import React, { useContext } from "react";
import WithResults from "./withResults";
import SingleResult from "../singleResult/Primary";
import { PrimarySearchTermContext } from "../../providers/PrimarySearchTermProvider";
const PrimaryResults = props => {
const { currentSearchTerm } = useContext(PrimarySearchTermContext);
const compare = (a, b) => {
if (a.resultCount > b.resultCount) return 1;
if (b.resultCount > a.resultCount) return -1;
return 0;
};
const renderResults = () => {
//According to requirements, this search starts showing results after the third character
if (props.results[0] === undefined || currentSearchTerm.length <= 2)
return null;
const relevantResults = [];
props.results[0]
.sort(compare)
.reverse()
.map(result => {
if (result.term.toLowerCase().includes(currentSearchTerm.toLowerCase()))
relevantResults.push(result);
});
return relevantResults.slice(0, 4).map(result => {
if (currentSearchTerm === result.term) return null;
return (
<SingleResult
searchTerm={currentSearchTerm}
term={result.term}
resultCount={result.resultCount}
key={result.term}
/>
);
});
};
return <div className="results">{renderResults()}</div>;
};
export default WithResults(PrimaryResults);
我不断收到的错误是包装组件中导出的最后一行。
解决方案
所以像这样导出最终解决了我的问题:
const composedWithResults = compose(connect(mapStateToProps, null), withResults);
export default composedWithResults;
作为一个初学者,我会诚实地说我不知道为什么,但它确实有效。一个解释表的人会很好。
推荐阅读
- java - 为什么 ChronoLocalDate 和 ChronoLocalDateTime 被设计成完全不同的接口?
- java - 如何停止在 java 组合框中复制项目
- data-structures - 这段代码的空间复杂度是多少
- python - 使用 pytorch (LSTM) 预测未来 60 天
- postgresql - 护照书架没有将用户插入数据库
- reactjs - Typescript + Jest:导入在 jest 与开发模式中是不同的
- c# - Azure 应用服务限制 - 允许应用服务 A 用于应用服务 B
- python - 有没有办法将 python 模块组合到一个文件中?
- android - 2 显示广告时使用回收站视图getItemcount 方法列出?
- java - Spring Thymeleaf 缩短 url (form-get) 参数