我只是尝试将简单的 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 的组件是从与 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 可用。
如何解决:
- 有序导出:
在 ./components/index.js 中,根据您的依赖项更改导出顺序:
// just using the "re-export" shortcut
export { default as withOptions } from "./Options";
export { default as BilanClimatique } from "./BilanClimatique";
我不会推荐它。它非常脆弱。
- 使用 index.js 仅向您的命名空间外部公开。在您的命名空间内,依赖显式导入。
即在 ./components/BilanClimatique.js 中:
import withOptions from "./Options";
- 如果您的代码库非常大,请使用多个 index.js 导出您的“契约(Contract)”。看看各种库作者的代码库,我认为这是他们采取的策略。
除非您在使用 #2 时遇到问题,否则我个人会推荐 #2 而不是 #3。
关于javascript - HOC import TypeError : Object(. ..) 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51626311/