简体   繁体   English

React:组件是否在每个 setState() 上完全重新渲染?

[英]React: Is a component entirely re-rendered on every setState()?

Just got a bit confused about the lifecycle in react.只是对反应的生命周期有点困惑。 Here's my understanding...以下是我的理解...

The render() always run first, right? render()总是先运行,对吧? If so...如果是这样...
It implies that a setState() inside useEffect() only runs after the initial render() , correct?这意味着useEffect()中的setState() ) 仅在初始render()之后运行,对吗?

Question:问题:
When the above happens, does the entire component re-render?当上述情况发生时,整个组件是否会重新渲染?
So that would be a second time the component renders just to load a state .所以这将是组件第二次渲染只是为了加载state
Wouldn't that be a performance issue?这不会是性能问题吗?

On every state change render is called again but not whole component renders again.在每个 state 上,都会再次调用更改渲染,但不会再次渲染整个组件。

React keeps Two DOM Tree Objects in memory: React 在 memory 中保留了两个 DOM 树对象:

  1. Virtual DOM虚拟 DOM
  2. Real DOM真实的 DOM

React have a very intelligent and powerful diffing algorithm which calculates difference between previous DOM state and Next DOM state called Reconciliation process. React 有一个非常智能且强大的 diffing 算法,它计算之前的 DOM state和 Next DOM state之间的差异,称为Reconciliation过程。

Only those sub elements which have changed would be re-rendered.只有那些已经改变的子元素会被重新渲染。
Keys help React identify which items have changed, are added, or are removed.键帮助 React 识别哪些项目已更改、添加或删除。
Keys should added to list or array elements, to give those elements a stable identity应将键添加到listarray元素中,以使这些元素具有稳定的身份

在此处输入图像描述

For example, you want to delete <input key="i42"/> element from your list so on left side Its Actual DOM Tree Object and on Right side its Virtual DOM tree object .例如,您想从列表中删除<input key="i42"/>元素,因此在左侧其实际 DOM 树 Object和右侧其虚拟 DOM 树 object React calculates difference between two and only the difference will be Recreated Intelligently. React 计算两者之间的差异,只有差异会被智能地重新创建。

https://reactjs.org/docs/lists-and-keys.html https://reactjs.org/docs/lists-and-keys.html

https://reactjs.org/docs/reconciliation.html#the-diffing-algorithm https://reactjs.org/docs/reconciliation.html#the-diffing-algorithm

So the thing about React is that there are two DOMs -- one is the actual DOM, and the other is the virtual DOM.所以关于 React 的事情是有两个 DOM——一个是实际的 DOM,另一个是虚拟的 DOM。 Every time there is a state change, the virtual DOM re-renders.每次发生 state 更改时,虚拟 DOM 都会重新渲染。 React then compares the changes to the virtual DOM vs changes to the real DOM, and only updates the real DOM with what has actually changed.然后,React 将虚拟 DOM 的更改与真实 DOM 的更改进行比较,并且仅使用实际更改的内容更新真实 DOM。 Re-rendering the virtual DOM is not a performance issue as it's super quick.重新渲染虚拟 DOM 不是性能问题,因为它超级快。

There's a cool article you can read about this您可以阅读一篇很酷的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM