【问题标题】:Did not expect server HTML to contain a <div> in <main>没想到服务器 HTML 在 <main> 中包含 <div>
【发布时间】:2020-01-03 15:15:34
【问题描述】:

我正在从事的项目使用:

  • react/react-dom@16.9.0
  • @loadable/组件
  • 样式化组件
  • react-router-dom

应用程序呈现服务器端和客户端端。

我正在使用@loadable/component 以这种方式动态代码拆分。

路由器.tsx

import * as React from 'react'
import loadable from '@loadable/component'
import { Route, Switch } from 'react-router-dom'

const NotFound = loadable(() =>
  import('../components/NotFound/NotFound' /* webpackChunkName: "notfound" */)
)

const routes = (
  <Switch>
    <Route component={NotFound} />
  </Switch>
)

export default routes

加载页面时,控制台上出现此错误,页面似乎闪烁了一秒钟。

react-dom.development.js:546 Warning: Did not expect server HTML to contain a <div> in <main>.

当我检查双方(服务器/客户端)的输出时,它们相同

当我像下面这样删除@loadable/component 时,它可以工作并且错误消失了。

router-without-loadable.tsx

import * as React from 'react'
import { Route, Switch } from 'react-router-dom'
import NotFound from '../components/NotFound/NotFound'

const routes = (
  <Switch>
    <Route component={NotFound} />
  </Switch>
)

export default routes

似乎与 @loadable/component 有关,但我不是 100% 确定。

【问题讨论】:

  • @loadable 用于 SSR,这意味着您的页面在服务器端编译并作为 HTML 发送到客户端
  • 是的,HTML 不是发送到客户端,而是作为响应发送到浏览器。但是,是的,我的问题与动态导入有关。

标签: javascript reactjs react-router-dom server-side-rendering loadable-component


【解决方案1】:

终于有答案了:

  1. 要让@loadable/component 正常工作,您需要在文件路径前添加魔术 webpack 注释 (/* webpackChunkName: "notfound" */)。
const NotFound = loadable(() =>
  import(/* webpackChunkName: "notfound" */ '../components/NotFound/NotFound')
)

参考:

https://github.com/smooth-code/loadable-components/issues/23

  1. 更重要的是,在服务器端,您需要将应用包装在 ChunkExtractorManager 中并传递客户端提取器(我传递的是服务器提取器,文档中不太清楚)。
const statsFile = path.resolve('./wwwroot/dist/loadable-stats.json')
const extractor = new ChunkExtractor({ 
  statsFile, 
  entrypoints: ['client'] // name of the proper webpack endpoint (default: main)
})

<ChunkExtractorManager extractor={extractor}>
  <App />
</ChunkExtractorManager>

这是一个关于如何实现它的正确清晰示例:

https://github.com/iamssen/seed

24.09.2019 更新

添加到官方文档中

https://www.smooth-code.com/open-source/loadable-components/docs/server-side-rendering/#chunkextractor-entrypoints

【讨论】:

    【解决方案2】:

    我认为问题在于您的 NotFound 组件未加载,因此 Route 不知道要渲染什么导致错误。

    您需要修改如下内容:

    <Route path="/404/" exact component={props => <NotFound {...props} />} />
    

    【讨论】:

    • NotFound 组件在服务器和客户端中完美呈现,正如我所说,输出是相同的。这就是为什么我想知道为什么当我添加动态导入不起作用而当我删除它们时它确实起作用。这与路由器无关,否则无论有没有动态导入,它都不会工作,如果它有意义的话。
    猜你喜欢
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 2021-08-19
    • 2019-10-26
    • 2021-01-15
    • 2013-03-13
    • 2020-07-04
    相关资源
    最近更新 更多