javascript - HOC import TypeError : Object(. ..) 不是函数

标签 javascript reactjs

我只是尝试将简单的 HOC 与 React 结合使用。 这是函数:

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 error

谁能帮我理解一下?

编辑:

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

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

export {
  withOptions,
  BilanClimatique
}

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

最佳答案

这似乎是提升“导出”的问题。据我所见,imports 得到 hoisted ,但我看不到任何与 exports 类似的内容。

导致问题的流程(codesandbox):

应用程序.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 导出您的“契约(Contract)”。看看各种库作者的代码库,我认为这是他们采取的策略。

除非您在使用 #2 时遇到问题,否则我个人会推荐 #2 而不是 #3。

关于javascript - HOC import TypeError : Object(. ..) 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51626311/

相关文章:

javascript - 如何访问 Google Earth Engine 中列表中的元素

javascript - 如果路径包含目录

reactjs - 显示重复图像 - useEffect 问题?

javascript - react组件如何传值给上一个页面组件

html - CSS 变换移动点击处理程序?

javascript - 在 mouseenter 上的 jQuery 插件中访问 DOM 元素

javascript - 如何使用 Cassandra 手动分页导航到上一页

javascript - Reactjs 中的 changedropdown 更新数据被延迟

reactjs - react Prop 与 child 。什么时候用什么?

javascript - 使用 PhantomJS 从 CouchDB 获取文档