TypeError: Object(...) is not a function when doing compose on ReactJS HOC

TypeError: Object(...) is not a function when doing compose on ReactJS HOC

我有一个尝试组合的组件(从“compose-function”库导入),如下所示;

export function MyRoute() {
  let MyGridWithData = compose(
    withRouter,
    withTranslation("translations"),
    withMyApi()
  )(MyGrid);
  return <MyGridWithData />;
}

但是,由于某种原因,我看到了以下错误;

TypeError: Object(...) is not a function

在线上指出错误;让 MyGridWithData = 撰写(...)

此外,虽然 withRouter 和 withTranslation 是标准钩子,但 withMyApi 定义如下(基本上是 HOF);

export function withMyApi() {
  // Extra function wrapper 
  return function(WrappedComponent) {
    class MyApiUrls extends React.Component {
      constructor(props) {
        super(props);
      }

      render() {
        return <WrappedComponent api={this.api} {...this.props} />;
      }
    }
    return MyApiUrls;
  };
}

一切看起来都是正确的,除了;可能您错误地导入了 compose 函数。

这是一个默认的导出,不是命名的。所以,正确的导入方式是:

import compose from 'compose-function';

旁注:Don’t Use HOCs Inside the render Method as it similar to 。所以,你应该写成:

const MyGridWithData = compose(
    withRouter,
    withTranslation("translations"),
    withMyApi()
  )(MyGrid);

export function MyRoute() {
  // more code if any
  return <MyGridWithData />;
}