In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to realize the principle of react rendering". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to realize the principle of react rendering.
1. JSX
So first let's take a look at the simple React component, the code is as follows:
Import React from 'react';export default function App () {return (Hello React);}
The syntax we use in this code is called JSX, which is the syntax sugar of the React.createElement method, we can achieve separation of concerns by using JSX to directly show UI and interaction, and the top of each react group price has to import React, because JSX actually relies on Babel (@ bable/preset-react) to transform the syntax and finally generate the nested syntax of React.createElement that we need. Let's take a look at the rendered result of JSX conversion. The code is as follows:
Function App () {return React.createElement ('div', {className:' App',}, React.createElement ('H2, null, 'Hello React'));}
II. CreateElement
The createElement () party is as follows:
React.createElement (type, [props], [... children])
CreateElement () takes three parameters, which we can tell in the code are the element type, attribute value and child element values, and it will eventually generate Virtual DOM. We now print the component content to our console.
We can see from the screenshot that Virtual DOM is essentially a JS object, so we store node information by key-value pairs and use nesting to represent the hierarchical relationship between nodes. Then using VDOM can avoid frequent DOM operations and create conditions for the following React Diff algorithm. So let's go back to our createElement () method and take a look at how it produces VDOM.
III. Simplified version of createElement () method
First, we get all the parameters through the createElement () method by traversing the config, then get the values of its child nodes and the default Props, and then we return the JS object after passing the value to the ReactElement () call.
What is worth noting in the screenshot is that each react component is identified using $$typeof, and its value uses Symbol data structures to ensure uniqueness.
IV. ReactDOM.render
Through the above steps, we get VDOM,react through the coordination algorithm (reconciliation) to compare the VDOM before and after the update, so as to find the minimum operation that needs to be updated to reduce the cost of operating DOM multiple times. As we traverse the component tree, as the component becomes larger and larger, the higher our recursive traversal cost will be, so we have the following solution.
Render () method:
ReactDOM.render (element, container [, callback])
In this case, we also need to understand how ReactDOM.render constructs fiber tree. In fact, legacyRenderSubtreeIntoContainer is actually called in ReactDOM.render. The following is the calling process. The code is as follows:
ReactDOM = {render (element, container, callback) {return legacyRenderSubtreeIntoContainer (null, element, container, false, callback);},}
I think everyone is familiar with the element and container in the code, but the callback in the code is a callback function that needs to be executed after rendering is complete.
Next, let's look at the definition of the method. The code is as follows:
Function legacyRenderSubtreeIntoContainer (parentComponent, children, container, forceHydrate, callback) {let root = container._reactRootContainer; let fiberRoot; / / first render if (! root) {/ / initialize mount, get the React root container object root = container._reactRootContainer = legacyCreateRootFromDOMContainer (container, forceHydrate); fiberRoot = root._internalRoot / / initialization installation does not require batch updates, and unbatchedUpdates (() = > {updateContainer (children, fiberRoot, parentComponent, callback);});} else {fiberRoot = root._internalRoot; updateContainer (children, fiberRoot, parentComponent, callback);} return getPublicRootInstance (fiberRoot);}
We can see that in the code, because the mount is root, we need to set the value of parentComponent to null
In addition, the other parameter forceHydrate represents whether it is server-side rendering or not, because the render () method is called here to render for the client side, so it defaults to false.
Because this is the first time it is mounted, root cannot get a value from container._reactRootContainer, so it creates a FiberRoot object. Moreover, server rendering is taken into account in the process of creating FiberRoot objects, and there are many calls between functions, so the core method of the final call is shown here. The code is as follows:
/ create fiberRoot and rootFiber and mutually reference function createFiberRoot (containerInfo, tag, hydrate, hydrationCallbacks) {const root = new FiberRootNode (containerInfo, tag, hydrate); if (enableSuspenseCallback) {root.hydrationCallbacks = hydrationCallbacks;} / / create the root node of fiber tree, that is, rootFiber const uninitializedFiber = createHostRootFiber (tag); root.current = uninitializedFiber; uninitializedFiber.stateNode = root; initializeUpdateQueue (uninitializedFiber); return root;}
We can see from the code that in this method, containerInfo is the root node, while tag is the tag of the FiberRoot node, which is changed to LegacyRoot. And the other two parameters are related to server rendering. In the code, the FiberRoot object is created using the FiberRootNode method, and the RootFiber object is created using the createHostRootFiber method, so that the current in the FiberRoot points to the stateNode of the RootFiber,RootFiber and points to the FiberRoot, thus forming a mutual reference.
The following two constructors show some of the important properties of fiberRoot and rootFiber.
FiberRootNode part of the attribute, the code is as follows:
Function FiberRootNode (containerInfo, tag, hydrate) {/ / the type used to mark fiberRoot this.tag = tag; / / points to the currently active corresponding rootFiber node this.current = null; / / and related information about the DOM container associated with fiberRoot this.containerInfo = containerInfo; / / whether the current fiberRoot is in hydrate mode this.hydrate = hydrate / / only one task is maintained on each fiberRoot instance, which is saved in the callbackNode attribute this.callbackNode = null; / / priority of the current task this.callbackPriority = NoPriority;}
Some of the property codes for the Fiber Node constructor are as follows:
Function FiberNode (tag, pendingProps, key, mode) {/ / rootFiber points to fiberRoot,child fiber points to corresponding component instance this.stateNode = null; / / return attribute always points to parent node this.return = null; / / child attribute always points to first child node this.child = null; / / sibling attribute always points to first sibling node this.sibling = null / / indicates the update queue, for example, in common setState operations, the data that needs to be updated will be stored in the updateQueue queue for subsequent scheduling this.updateQueue = null; / / indicates the expiration time of the current update task, that is, after this time, the update task will be completed this.expirationTime = NoWork;}
The resulting fiber tree structure
5. React Diff algorithm
For react, it is not faster than native DOM, but in large applications, we often do not need to re-render every time, so we can let react update the necessary DOM through VCOM and diff algorithm.
At this point, I believe that everyone on the "react rendering principle how to achieve" have a deeper understanding, might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.