代码 splitting/react-loadable 问题

Code splitting/react-loadable issue

我正在尝试使用 react-loadable 将代码拆分引入我的应用程序。我在一个非常简单的组件上试了一下:

const LoadableComponent = Loadable({
    loader: () => import('components/Shared/Logo/Logo'),
    loading: <div>loading</div>,
});

然而,当渲染这个组件时,我得到以下错误:

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `LoadableComponent`.
    in LoadableComponent (created by AppHeader)
    in div (created by AppHeader)
    in AppHeader (created by PlainChatApp)
    in div (created by PlainChatApp)
    in PlainChatApp (created by DragDropContext(PlainChatApp))
    in DragDropContext(PlainChatApp) (created by Connect(DragDropContext(PlainChatApp)))
    in Connect(DragDropContext(PlainChatApp))
    in Provider
    in AppContainer
    in ErrorBoundary

The above error occurred in the <LoadableComponent> component:
    in LoadableComponent (created by AppHeader)
    in div (created by AppHeader)
    in AppHeader (created by PlainChatApp)
    in div (created by PlainChatApp)
    in PlainChatApp (created by DragDropContext(PlainChatApp))
    in DragDropContext(PlainChatApp) (created by Connect(DragDropContext(PlainChatApp)))
    in Connect(DragDropContext(PlainChatApp))
    in Provider
    in AppContainer
    in ErrorBoundary

我没有发现任何明显的错误,而且我无法在该存储库中提出问题。

事实证明,您需要将组件传递给 loading 选项而不是 JSX。文档上说的很清楚,我只是错过了。

不要将 jsx 传递给 Loadable 组件的加载键,提供有效的 React 组件。

const LoadableComponent = Loadable({
    loader: () => import('components/Shared/Logo/Logo'),
    loading: () => <div>loading</div>, // pass component, not jsx
});

对于因为服务器端渲染应用程序(服务器 babel 转译文件)吐出上述错误而来到这里的人,这可能是因为您使用的是 airbnb babel-plugin-dynamic-import-node 而没有设置noInterop.babelrc 上变为 false,如下所示: { "plugins": [ ["dynamic-import-node", { "noInterop": true }] ] }


请务必使用 default exports,因为当您导入时它不会使用命名导出:loader: () => import(/* webpackChunkName: "home" */ './Home')