【发布时间】:2018-12-15 21:38:08
【问题描述】:
这基本上是我的所有代码。我正在运行 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 []
我有点迷茫,因为它应该可以工作.. 一切看起来都很好。
【问题讨论】:
-
即使使用 preloadAll(),我也处于类似的状态。我快疯了,因为我的代码看起来与我能找到的每个示例都相同,但是即使服务器渲染工作完美,模块总是返回空。
-
我将在本周末发布我的工作代码作为答案@soutarm
-
这里有什么消息吗?我有同样的问题......(并且 preloadAll() 没有帮助)
标签: node.js webpack react-router-v4 react-dom react-loadable