最近,我研究了Facebook的React框架。它使用了一个叫做“虚拟DOM”的概念,我并不真正理解这个概念。

什么是虚拟DOM?它的优点是什么?


当前回答

虚拟Dom是创建Dom的一个副本。虚拟dom与dom比较,虚拟dom只更新dom中发生变化的部分。它没有渲染整个dom它只是改变了dom中dom的更新部分。这是非常耗时的,从这个功能,我们的应用程序工作得很快。

其他回答

虚拟Dom是创建Dom的一个副本。虚拟dom与dom比较,虚拟dom只更新dom中发生变化的部分。它没有渲染整个dom它只是改变了dom中dom的更新部分。这是非常耗时的,从这个功能,我们的应用程序工作得很快。

虚拟DOM是HTML DOM的抽象,它根据状态变化选择性地呈现节点的子树。它尽可能少地进行DOM操作,以使组件保持最新状态。

这是一个简洁的概念:不直接操作DOM(容易出错并且依赖于可变状态),而是输出一个名为Virtual DOM的值。然后,虚拟DOM与DOM的当前状态进行区分,这会生成一个DOM操作列表,使当前DOM看起来像新DOM。这些操作在批量中快速应用。

从这里拍的。

虚拟DOM(VDOM)并不是一个新概念:https://github.com/Matt-Esch/virtual-dom。

VDOM在战略上更新DOM,而不需要重新绘制单个页面应用程序中的所有节点。在树结构中找到一个节点很容易,但SPA应用程序的DOM树可能非常大。在事件发生时查找和更新一个/多个节点并不省时。

VDOM通过创建实际dom的高级抽象来解决这个问题。VDOM是实际DOM的高级轻量级内存树表示。

例如,考虑在DOM中添加一个节点;在内存中保留一个VDOM副本

创建带有新状态的VDOM 将它与使用差分的旧VDOM进行比较。 只更新真实DOM中的不同节点。 将新的VDOM分配为旧的VDOM。

这是对ReactJS中经常提到的Virtual DOM的简要描述和重申。

The DOM (Document Object Model) is an abstraction of structured text, which means it is made of HTML code and css. These HTML elements become nodes in the DOM. There are limitations to the previous methods of manipulating the DOM. Virtual DOM is an abstraction of the literal HTML DOM created well before React was created or used, but for our purposes we will use it in concert with ReactJS. The Virtual DOM is lightweight and detached from the DOM implementation in the browser. The Virtual DOM is essentially a screenshot (or copy) of the DOM at a given time. A way to look at it from a developers perspective is the DOM is the production environment and the Virtual DOM is the local (dev) environment. Each time the data changes in a React app a new Virtual DOM representation of the user interface is created.

为了在ReactJS中创建静态组件,最基本的方法是:

必须从呈现方法返回代码。 您必须将每个类转换为className,因为class是JavaScript中的保留字。 除了更大的变化之外,两个DOM之间还有一些小差异,包括虚拟DOM中出现而HTML DOM中没有出现的三个属性(key、ref和dangerlysetinnerhtml)。

在使用Virtual DOM时,需要理解的一件重要事情是ReactElement和ReactComponent之间的区别。

ReactElement

ReactElement是DOM元素的轻量级、无状态、不可变的虚拟表示。 ReactElement -这是React中的主要类型,位于Virtual DOM中。 ReactElements可以被渲染成HTML DOM var root = React.createElement('div'); ReactDOM。呈现(根,. getelementbyid(例子)); JSX将HTML标记编译为ReactElements Var root = <div/>; ReactDOM。呈现(根,. getelementbyid(例子));

ReactComponent

ReactComponent——ReactComponent是有状态的组件。 反应。createClass被认为是一个ReactComponent。 每当状态改变时,组件都会被重新呈现。

每当ReactComponent发生状态变化时,我们希望对HTML DOM的更改尽可能少,这样ReactComponent就可以转换为ReactElement,然后ReactElement可以插入到Virtual DOM中,快速方便地进行比较和更新。

当React知道diff时,它会被转换为低级代码(HTML DOM),并在DOM中执行。