javascript - 更新渲染元素(不可变)

标签 javascript reactjs

React tutorial , 它说

React elements are immutable. Once you create an element, you can’t change its children or attributes. An element is like a single frame in a movie: it represents the UI at a certain point in time. With our knowledge so far, the only way to update the UI is to create a new element and pass it to ReactDOM.render().

在下一个标题中,它说

React 只更新必要的内容

React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.

他们举的例子-

function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
  );
  ReactDOM.render(element, document.getElementById('root'));
}

setInterval(tick, 1000);

在此示例中,React 仅更新时间 - <h2>It is {new Date().toLocaleTimeString()}.</h2 > 代码行。因为这只是必要的更改,但我无法理解 React 如何像他们提到的那样更改不可变对象(immutable对象)

React elements are immutable. Once you create an element, you can’t change its children or attributes.

因此,与其只更改(上述代码示例的)“Just Time Part”,不如更改整个 React 元素。 我无法理解 React 如何在 Immutable 对象(在上面的例子中是元素)内进行必要的更新,或者我遗漏了什么?

最佳答案

它不会对 React 元素树(“不可变对象(immutable对象)”)进行更新。它将之前的树与当前的树进行比较,并对 DOM 进行必要的更新。

React Element Tree 是 DOM 的简化形式。这就像一个快照。 React 拥有当前快照,当应用程序的状态发生变化时,它会创建一个新状态来反射(reflect) DOM 的外观。 React 比较这两个快照并对 DOM 进行必要的更改,以便它镜像新的快照。之后旧的、过时的快照被丢弃,新的成为 DOM 的当前快照。

基本上,你有:

  • 应用的状态
  • 描述应用程序在给定状态下的样子(您编写的 React 代码)
  • 快照(React 元素树)
  • 区分和更新机制(React 库)
  • DOM

DOM 或外部世界(即服务器)产生改变状态的事件。根据描述为该状态创建新快照。比较新旧快照并将更改引入 DOM。这个过程一遍又一遍地重复。

您可以在这篇精彩的博文中查看和了解有关 React 元素的更多信息:https://reactjs.org/blog/2015/12/18/react-components-elements-and-instances.html

关于javascript - 更新渲染元素(不可变),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52460185/

相关文章:

javascript - 异步函数回调返回值

javascript - Next.js:带状态的 Router.push

javascript - React中定义方法的两种方式,有什么不同?

reactjs - 如何在 js 网络应用程序中保持身份验证 token 的安全?

cqrs - 对 React 的 Flux 架构感到困惑 - waitFor

javascript - 即时创建 React 上下文菜单

javascript - FancyBox 无法打开外部页面的链接

javascript - Angular 2 与 TypeScript : View not updating after setting variable in response handler

javascript - 从node.js中的对象导出内部函数

javascript - 根据 TD 类别隐藏 TR