Calling render vs painting the DOM?

回眸只為那壹抹淺笑 提交于 2019-12-11 06:42:30

问题


I’m learning about React and trying to get a better understanding about the lifecycle and about the different stages.

One thing I just read states “React first renders and then mounts elements. Rendering in this context means calling a class’s render(), not painting the DOM”

I guess I just don’t really get what that means. Can someone explain it in a simple way or with examples?

Thanks in advance!


回答1:


Some simplified definitions first:

  1. Browser uses dom to decide what to display. In react, this is referred to as painting, because whenever something is added to a dom, browser has to re-paint the screen.
  2. dom manipulations are costly. Either in time or resources
  3. One of the reasons react looks so fast is that it uses something people call a virtual dom. Virtual dom tries to mirror the actual dom, they might be out of sync for a while, as all changes to virtual dom are not reflected on the actual dom immediately (else what would be the benefit of having a virtual dom?)

With these definitions in mind, let us take a look at what React does:

  1. When react will fire render methods to populate its virtual dom
  2. It will keep batching the changes to the virtual dom, and once it determines a good time to change the screen, it will flush only the changes to the dom. This is called painting.

React uses a lot of optimization under the hood, I don't know all of them (would also argue, that I don't need to know what they do), but here are somethings to remember:

  1. As long as your render method is returning the same thing, react will do nothing on the screen.
  2. It is thus expected that react may call render method multiple times, even when you don't expect it to.
  3. It is thus recommended to keep your render method as free of any side effects or any resource intensive operations, such as fetching data, or transforming your data structure. Think of it as: render method should only have logic related to what needs to be rendered, anything else that it may need to do that, can be calculated outside and put in state or variables or even memoized.


来源:https://stackoverflow.com/questions/48437594/calling-render-vs-painting-the-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!