【问题标题】:TypeError: Object(...) is not a function when doing compose on ReactJS HOCTypeError:在 ReactJS HOC 上进行撰写时,Object(...) 不是函数
【发布时间】:2021-06-26 18:06:49
【问题描述】:

我有一个组件,我尝试编写(从“compose-function”库导入)如下;

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

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

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

错误指向了行;让 MyGridWithData = compose(...)

另外,虽然 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;
  };
}

【问题讨论】:

    标签: reactjs react-hooks react-hoc


    【解决方案1】:

    所有看起来都正确,除了;可能您错误地导入了compose 函数。

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

    import compose from 'compose-function';
    

    旁注:Don’t Use HOCs Inside the render Method 类似于re-creating a component at every re-render。所以,你应该写成:

    const MyGridWithData = compose(
        withRouter,
        withTranslation("translations"),
        withMyApi()
      )(MyGrid);
    
    export function MyRoute() {
      // more code if any
      return <MyGridWithData />;
    }
    

    【讨论】:

    • 哦……我的错!很抱歉……这么愚蠢的事情!感谢您指出这一点!
    • 当然,我记得……这么棒的人我怎么能忘记:)
    猜你喜欢
    • 1970-01-01
    • 2022-07-27
    • 2019-08-28
    • 2019-08-12
    • 2018-10-25
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 2019-06-11
    相关资源
    最近更新 更多