ReactJS服务器端呈现与客户端呈现 [英] ReactJS server-side rendering vs client-side rendering

查看:339
本文介绍了ReactJS服务器端呈现与客户端呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始研究ReactJS并发现它为您提供了两种呈现页面的方式:服务器端和客户端。但是,我无法理解如何一起使用它。它是构建应用程序的两种不同方式,还是可以一起使用?

I just have began to study ReactJS and found that it gives you 2 ways to render pages: server-side and client-side. But, I can't understand how to use it together. Is it 2 separate ways to build the application, or can they be used together?

如果我们可以一起使用它,怎么做 - 我们是否需要在服务器端和客户端复制相同的元素?或者,我们可以在服务器上构建应用程序的静态部分,以及客户端上的动态部分,而不与已经预呈现的服务器端建立任何连接吗?

If we can use it together, how to do it - do we need to duplicate the same elements on the server side and client side? Or, can we just build the static parts of our application on the server, and the dynamic parts on the client side, without any connection to the server side that was already pre-rendered?

推荐答案

对于给定的网站/网络应用程序,您可以使用客户端服务器端两者

For a given website / web-application, you can use react either client-side, server-side or both.

在这里,您完全运行ReactJS在浏览器上。这是最简单的设置,包括大多数示例(包括 http://reactjs.org 上的示例)。服务器呈现的初始HTML是占位符,一旦所有脚本加载,整个UI就会在浏览器中呈现。

Over here, you are completely running ReactJS on the browser. This is the simplest setup and includes most examples (including the ones on http://reactjs.org). The initial HTML rendered by the server is a placeholder and the entire UI is rendered in the browser once all your scripts load.

将ReactJS视为服务器端模板引擎(如玉器,车把等......)。服务器呈现的HTML包含应该使用的UI,您不必等待加载任何脚本。您的页面可以被搜索引擎编入索引(如果没有执行任何javascript)。

Think of ReactJS as a server-side templating engine here (like jade, handlebars, etc...). The HTML rendered by the server contains the UI as it should be and you do not wait for any scripts to load. Your page can be indexed by a search engine (if one does not execute any javascript).

由于UI是在服务器上呈现的,因此您的事件处理程序都不起作用并且没有交互性(你有一个静态页面)。

Since the UI is rendered on the server, none of your event handlers would work and there's no interactivity (you have a static page).

这里,初始渲染是打开的服务器。因此,浏览器接收的HTML具有应有的UI。加载脚本后,再次重新呈现虚拟DOM以设置组件的事件处理程序。

Here, the initial render is on the server. Hence, the HTML received by the browser has the UI as it should be. Once the scripts are loaded, the virtual DOM is re-rendered once again to set up your components' event handlers.

在这里,您需要确保重新创建 - 使用您在服务器上呈现的相同 props 完全相同的虚拟DOM(根ReactJS组件)。否则,ReactJS会抱怨服务器端和客户端虚拟DOM不匹配。

Over here, you need to make sure that you re-render the exact same virtual DOM (root ReactJS component) with the same props that you used to render on the server. Otherwise, ReactJS will complain that the server-side and client-side virtual DOMs don't match.

由于ReactJS在重新渲染之间区分虚拟DOM,因此真正的DOM没有变异。只有事件处理程序绑定到真正的DOM元素。

Since ReactJS diffs the virtual DOMs between re-renders, the real DOM is not mutated. Only the event handlers are bound to the real DOM elements.

这篇关于ReactJS服务器端呈现与客户端呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆