0

我试图在这里和其他帖子中阅读接受的答案,但不能放弃弄清楚这是否对我有帮助。我觉得那里的情况有所不同。

我已经看过一些关于如何使用 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);

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

4

4 回答 4

0

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

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

export default composedWithResults;

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

于 2019-12-31T07:37:41.033 回答
0

尝试像这样导出:

const withResultHoc = connect(mapStateToProps)(withResults);
export default withResultHoc;
于 2019-12-30T13:55:57.747 回答
0

尝试这个: export default compose(withResult, connect(.....))(PrimaryResults)

于 2019-12-30T14:41:26.727 回答
0

在你的 HOC 中试试这个:

 export default (WrappedComponent) => connect(mapStateToProps)(withResults(WrappedComponent));
于 2021-04-27T10:02:58.127 回答