本文介绍了SSR:React应用程序中的动态导入在客户端上加载组件时如何处理html Miss匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Webpack 4和react-loadable,我刚刚开始在服务器端使用代码拆分和动态导入渲染React 16应用程序。

I'm just starting on server side rendering a react 16 app using code splitting and dynamic import thanks to webpack 4 and react-loadable.

我的问题可能听起来像

在服务器端,我正在等待webpack加载所有模块,然后将html吐出到客户端。

On the server side, I'm waiting that webpack has loaded all modules before spitting out the html to the client.

在客户端,在渲染已加载的组件之前,我已经渲染了一种加载组件。

On the client side I have a kind of loading component rendered, before rendering the loaded component.

所以基本上,服务器呈现了已加载的组件:

So basically the server renders the loaded component:

<div>loaded component</div>

然后客户端为加载组件补水:

And the client hydrates the loading component:

<div>loading...</div>

显然,问题在于React在hydrat()之后抱怨,因为服务器和服务器之间缺少匹配

Obviously, The problem is that React complains after hydrate() because there is a miss match between server and client.

在几秒钟内,客户端首先渲染

During a few seconds the client first renders

<div>loading...</div>

而服务器已渲染并向客户端发送了已加载组件的html。

whereas server has rendered and sent to the client, the html of the loaded component.

有人可以启发我吗?究竟如何运作?
如何在加载组件时防止第一次渲染时出现不匹配?

Can someone enlighten me ? how does it work exactly ?How can I prevent a mismatch at first render when the component is being loaded ?

推荐答案

类似您没有在客户端中预加载

Loadable.preloadReady().then(() => {
  ReactDOM.hydrate(<App/>, document.getElementById('app'));
});

这也是避免的必要步骤水合不匹配

原因:

此问题是在您的客户端上引起的,因为初始请求,您的未加载,因此 html输出将是 loading ... 而不是组件内容本身。
只有在提取并加载了块之后,此初始状态 loading ... 才会被所需的内容替换。

This issue is caused on your client because the initial request, your chunks were not loaded, so the html output for those components would be loading... instead of the component content itself.Only after the chunks are fetched and loaded that this initial state loading... will be replaced by the desired content.

因此, Loadable.preloadReady 方法将创建一个 Promise ,该值为已解决,一旦应用程序块被预加载,以这种方式,拥有初始阶段所需的所有资产, ReactDOM.hydrate 将生成与以下内容相同的输出:

So, Loadable.preloadReady method creates a Promise that will be resolved once the application chunks were preloaded, in that way, having all assets needed for the initial stage, ReactDOM.hydrate will generate the same output as your server did.

提示

我也建议您看看 React Loadable SSR加载项,它是一个非常方便的加载项可以增强服务器端资产管理,为您带来与CSR(客户端渲染)相同的收益。

Also I recommend you to take a look at React Loadable SSR Add-on, it is a very handy add-on that will enhance your server side assets management, giving you the same benefits as it was CSR (Client Side Render).

请参见

这篇关于SSR:React应用程序中的动态导入在客户端上加载组件时如何处理html Miss匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:16