这基本上都是我的代码。我正在运行hapi并尝试使用react loadable to server呈现我的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

它正确地呈现页面,正如我在浏览器中看到的那样。尽管我看不到“路由器”的任何内容,除非我在服务器上禁用缓存。因此,第一个请求不呈现路由器,而下面的请求呈现路由器。
在服务器上,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 []

我有点迷路了,因为它应该起作用了。一切看起来都很好。

最佳答案

似乎即使您加载了组件,react loadable也不知道它们。
如果您使用Loadable.preloadAll而不是通过编程方式加载组件,那么它应该可以解决您的问题。
当路由数量增加时,您当前的方法也会变得非常冗长,您必须维护预加载的列表。

07-24 19:23