可加载.捕获不报告任何模块



这基本上是我所有的代码。我运行愉快,并尝试使用 react-loadable 来服务器渲染我的 React 应用程序。

我在这里的代码中添加了很多缺失的部分。

const location = req.url.pathname
const context = {}
const modules = []
const Router = () => (
<Switch>
<Route exact path="/" component={Home} />
<Route path="/login" component={Login} />
<Route path="/me" component={Profile} />
<Route component={NotFound} />
</Switch>
)
const App = () => (
<StaticRouter location={location} context={context}>
<main>
<Header />
<Router />
<Footer />
</main>
</StaticRouter>
)
const preloadables = [ Home, Login, Profile, NotFound ]
await Promise.all(preloadables.map(preloadable => preloadable.preload()))
const html = ReactDOMServer.renderToString(
<Loadable.Capture report={moduleName => modules.push(moduleName)}>
<App/>
</Loadable.Capture>
)
// render html

它正确呈现页面,因为我看到我的 React 应用程序在我的浏览器中呈现。尽管除非我在服务器上禁用缓存,否则我看不到"路由器"的任何内容。因此,第一个请求不呈现路由器,而下一个请求则呈现。

在服务器上,console.log('modules:', modules)始终返回modules: []。无论缓存如何。因此,即使我禁用缓存,刷新页面两次以查看路由器工作,模块仍然是空的。

npm run start:server
Warning: setState(...): Can only update a mounting component. This usually means you called setState() outside componentWillMount() on the server. This is a no-op.
Please check the code for the LoadableComponent component.
modules []
modules []
modules []
modules []
modules []

我有点迷茫,因为它应该可以工作......一切看起来都很好。

今天经过漫长的挣扎,终于解决了。

在获得模块之前,您必须正确编写可加载组件。官方文件在这里声明

Loadable({
loader: () => import('./Bar'),
modules: ['./Bar'],
webpack: () => [require.resolveWeak('./Bar')],
});

或者你可以使用提供的 babel 插件。但是,就我的情况而言,我使用的是 ts-node,并且没有运气使用该 babel 插件,因此只有选项 1 可用。

写在这里,因为有人会遇到类似的问题。

(附言lodable-component也依赖于 babel 插件(

似乎即使您加载了组件,反应加载也不知道它们。

如果您使用Loadable.preloadAll而不是以编程方式加载组件,它应该可以解决您的问题。

当路由数量增加时,您当前的方法也会变得非常冗长,您必须维护预加载项列表。

最新更新