【问题标题】:Loadable.Capture not reporting any modulesLoadable.Capture 不报告任何模块
【发布时间】: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


【解决方案1】:

今天不知怎么折腾了好久,终于解决了。

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

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

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

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

(p.s. lodable-component 也依赖 babel 插件)

【讨论】:

  • 这应该是公认的答案。谢谢,你拯救了我的一天!
  • @elaineee 不客气,很高兴能帮助像你这样的人。
【解决方案2】:

似乎即使您加载了组件,react-loadable 也不知道它们。

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

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

【讨论】:

  • 我也有类似的问题,因为我没有使用任何路由,所以匹配更简单。我正在使用 Loadable.preloadAll(),我在源代码中做了一些日志,并注意到所有相关模块确实都被它加载了。 SSR 应用程序在客户端和服务器上都能正常工作。唯一的问题是模块数组是空的,如开瓶器问题中所述。知道发生了什么吗?
猜你喜欢
  • 2013-04-11
  • 2011-11-06
  • 2019-01-14
  • 1970-01-01
  • 2018-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多