HOC 导入类型错误:Object(...) 不是函数

IT技术 javascript reactjs
2021-05-19 16:00:13

我只是尝试使用带有react的简单 HOC。这是功能:

import React from "react"

const withOptions = (WrappedComponent) => {

  return class extends React.Component {

    render() {
      return <WrappedComponent { ...this.props } />
    }
  }

}

export default withOptions

问题似乎出在我导出/导入它的方式上。

以简单的方式导入和使用,它的工作原理:

import withOptions from "./Options"
...

class BilanClimatique extends React.Component{
  ...
}
const StyledBilanClimatique = withStyles(styles)(BilanClimatique)
export default withOptions(StyledBilanClimatique)

但是如果我使用像 index.js 这样的中间文件

import withOptions from "./Options"

export {
  withOptions
}

并像这样将其导入到我的组件中

import {
  withOptions
} from "./index"

这是我得到的

高阶错误

有人可以帮助我理解这一点吗?

编辑 :

我发现使用 HOC 的组件是从与 HOC 相同的文件中导入的:

import withOptions from "./Options"
import BilanClimatique from "./BilanClimatique"

export {
  withOptions,
  BilanClimatique
}

这导致了问题,但我不明白为什么......这是一个有问题的沙箱https://codesandbox.io/s/r074735yvo

2个回答

这似乎是提升“出口”的问题。从我所看到的,imports吊起,但我看不到任何类似的东西exports

导致问题的流程(codeandbox):

应用程序.js:

import { BilanClimatique } from "./components/index";

./components/index.js:

// just using the "re-export" shortcut
export { default as BilanClimatique } from "./BilanClimatique";
export { default as withOptions } from "./Options";

./components/BilanClimatique.js:

import { withOptions } from "./index";

./components/Options.js:

const withOptions = WrappedComponent => {
  return ... //snipped code

export default withOptions;

当 App.js 向 index.js 询问 BilanClimatique 时,它​​反过来向相同的index.js询问withOptions. 但是由于导出似乎没有被提升,index.js 还没有使 withOptions 可用。

怎么解决:

  1. 订购出口:

在 ./components/index.js 中,根据您的依赖更改导出顺序:

// just using the "re-export" shortcut
export { default as withOptions } from "./Options";
export { default as BilanClimatique } from "./BilanClimatique";

我不会推荐它。它非常脆弱。

  1. 使用 index.js 只暴露给你的命名空间之外。在您的命名空间内,依赖显式导入。

即在 ./components/BilanClimatique.js 中:

import withOptions from "./Options";
  1. 如果您有一个非常大的代码库,请使用多个 index.js 来导出您的“合同”。看看各个库作者的代码库,我认为这就是他们采取的策略。

除非您遇到 #2 的问题,否则我个人会推荐 #2 而非 #3。

.看起来不是一个很好的导入路径。尝试从“索引”文件导入。

import {
  Logo,
  withOptions
} from "./index"