这基本上都是我的代码。我正在运行Hapi并尝试使用react-loadable来服务器渲染我的React应用程序。
我在代码here中添加了许多缺失的部分。
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.preloadAll
而不是以编程方式加载组件,它应该可以解决您的问题。
当路由数量增加时,您当前的方法也将变得非常冗长,您将必须维护可预加载的列表。
经过不知怎的漫长的斗争,终于解决了。
在获得模块之前,您必须正确编写可加载组件。官方文件宣布here
Loadable({
loader: () => import('./Bar'),
modules: ['./Bar'],
webpack: () => [require.resolveWeak('./Bar')],
});
或者您可以使用提供的babel插件。但是,作为我的情况,我使用ts节点并且没有运气使用该babel插件,因此只有选项1可用。
在这里写一个人会遇到类似的问题。
(p.s.lodable-component
也取决于babel插件)