问题
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:
- 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. dom
manipulations are costly. Either in time or resources- 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:
- When react will fire
render
methods to populate its virtual dom - 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:
- As long as your
render
method is returning the same thing, react will do nothing on the screen. - It is thus expected that react may call
render
method multiple times, even when you don't expect it to. - 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