首页 > 解决方案 > 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);

我不断收到的错误是包装组件中导出的最后一行。

标签: reactjshigher-order-componentshigh-order-component

解决方案


所以像这样导出最终解决了我的问题:

const composedWithResults = compose(connect(mapStateToProps, null), withResults);

export default composedWithResults;

作为一个初学者,我会诚实地说我不知道​​为什么,但它确实有效。一个解释表的人会很好。


推荐阅读