代码拆分/react加载问题

IT技术 reactjs code-splitting react-loadable
2021-05-23 17:36:20

我正在尝试使用 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

我没有看到任何明显的我做错了,而且我无法在该存储库中提交问题。

4个回答

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

确保使用,default exports因为在导入时它没有使用命名导出:loader: () => import(/* webpackChunkName: "home" */ './Home')

不要将 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为 false,.babelrc如下所示: { "plugins": [ ["dynamic-import-node", { "noInterop": true }] ] }