In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "some front-end basic knowledge collation and summary". In the daily operation, I believe that many people have doubts about some front-end basic knowledge collation and summary problems. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "some front-end basic knowledge collation and summary"! Next, please follow the editor to study!
React lifecycle
Lifecycle before React v16.0
Initialization (initialization) phase
There is only one lifecycle method for this phase: constructor.
Constructor ()
Used to do some component initialization work, such as defining the initial content of the this.state. If you do not initialize the state or bind the method, you do not need to implement the constructor for the React component. Why must super (props) be called first? Because the this object of the subclass must first be molded through the constructor of the parent class to get the same instance properties and methods as the parent class, and then process it, plus the subclass's own instance properties and methods. If you do not call the super method, the subclass will not get the this object.
Class Checkbox extends React.Component {constructor (props) {/ /? This super (props) cannot be used at this time; / / ✅ can now use this console.log (props); / / ✅ {} console.log (this.props); / / ✅ {} this.state = {};}}
Why does super send props?
It is necessary to pass props into super, which allows the base class React.Component to initialize this.props.
However, even if you don't pass in the props parameter when you call super (), you can still access this.props in render and other methods.
In fact, React sets the props for the instance again immediately after calling your constructor.
/ / React internal class Component {constructor (props) {this.props = props; / / initialize this.props / /...}} / / React internal const instance = new Button (props); instance.props = props; / / set props / / Button class component class Button extends React.Component {constructor (props) {super (); / /? We forgot to pass in props console.log (props); / / ✅ {} console.log (this.props); / /? Undefined}}
Mounting phase
Lifecycle method for this phase: componentWillMount = > render = > componentDidMount
1. ComponentWillMount ():
Called before the component is mounted to the DOM, and will only be called once.
Called immediately before each subcomponent render
Calling this.setState in this method does not cause the component to re-render, but you can also advance what is written here to constructor ().
2. Render (): the only method that must be implemented by class components
When render is called, it checks for changes in this.props and this.state and returns one of the following types:
React element. It is usually created through JSX. For example,
Will be rendered as a DOM node by React and as a custom component by React, whether
Or both are React elements.
Array or fragments. Enables the render method to return multiple elements. Fragments allows you to group sublists without adding additional nodes to the DOM.
Portals . You can render child nodes to different DOM subtrees. Portal provides an excellent scheme for rendering child nodes to DOM nodes that exist outside the parent component.
String or numeric type. They are rendered as text nodes in DOM.
Boolean type or null. Nothing is rendered.
The render () function should be a pure function, which means that without modifying the component state, the same result is returned on each call, and it does not interact directly with the browser. This.setState cannot be executed in it, which has the side effect of changing the state of the component.
3. ComponentDidMount
It will be called immediately after the component is mounted (inserted into the DOM tree) and will only be called once. Initialization that depends on the DOM node should be placed here.
The render is not called immediately, but only after all the subcomponents have finished render.
Update (update) phase
The lifecycle method for this phase is componentWillReceiveProps = > shouldComponentUpdate = > componentWillUpdate = > render = > componentDidUpdate.
React component update mechanism
The state update caused by setState or the props update caused by parent component re-render, the updated state and props will cause the child component to re-render regardless of whether there is any change or not.
1. Parent component re-render
Directly re-render. Whenever the parent component re-render causes the props to be retransmitted, the child component will be re-rendered directly, regardless of whether the props has changed. It can be optimized by shouldComponentUpdate method.
Update state before rendering. In the componentWillReceiveProps method, you convert props to your own state, and calling this.setState () will not cause a second rendering.
Because the componentWillReceiveProps determines whether the props has changed, if it changes, the this.setState will cause the state to change, thus causing the render, so there is no need to do the render caused by the retransmission of the props for the second time, otherwise the same rendering will be repeated.
two。 Own setState
The component itself calls setState, whether or not the state has changed. It can be optimized by shouldComponentUpdate method.
Life cycle analysis
1. ComponentWillReceiveProps (nextProps)
This method is called only during component updates caused by props, and is the only way to update in response to Props changes.
The parameter nextProps is the new props that the parent component passes to the current component. Judge whether the retransmitted props has changed according to nextProps and this.props, and deal with it accordingly.
2. ShouldComponentUpdate (nextProps, nextState)
Based on the return value of shouldComponentUpdate (), determine whether the output of the React component is affected by the current state or props change. The default behavior is to re-render the component each time the state changes.
When props or state changes, shouldComponentUpdate () is called before the rendering is executed. The default return value is true.
This method is not called the first time you render or use forceUpdate ().
This method can compare this.props with nextProps and this.state with nextState. When returning true, the current component will continue to perform the update process, while returning false will skip the update. This method can be used to reduce unnecessary rendering of components and optimize component performance.
Note that returning false does not prevent the child component from re-rendering when the state changes.
If you execute this.setState in componentWillReceiveProps () to update the state, but before the render (such as shouldComponentUpdate,componentWillUpdate), the this.state still points to the state before the update, otherwise the comparison between the nextState and the this.state of the current component will always be true.
Instead of writing shouldComponentUpdate () manually, you should consider using the built-in PureComponent component. PureComponent makes a shallow comparison between props and state and reduces the possibility of skipping the necessary updates.
3. ComponentWillUpdate (nextProps, nextState)
This method is executed before the render method is called, where you can perform some of the work before the component update occurs, which is generally rarely used.
4. Render
Render ditto
5. ComponentDidUpdate (prevProps, prevState)
This method is called immediately after the component is updated and can manipulate the DOM of the component update.
The parameters prevProps and prevState refer to props and state before the component is updated.
Unloading Pha
There is only one lifecycle approach to this phase: componentWillUnmount
ComponentWillUnmount
This method is called before the component is uninstalled, and you can perform some cleanup work here, such as knowing the timers used in the component, manually creating DOM elements in componentDidMount, and so on, to avoid memory leaks.
SetState () should not be called in componentWillUnmount () because the component will never re-render. After the component instance is uninstalled, it will never be mounted again.
Life cycle after React v16.0
When React v16.0 was first launched, a componentDidCatch lifecycle function was added, which is only an incremental modification and does not affect the original lifecycle function at all.
React v16.3, which introduces two new lifecycles: getDerivedStateFromProps,getSnapshotBeforeUpdate, scrapping componentWillMount, componentWillReceiveProps, and componentWillUpdate (available until React 17, with a warning).
Why change the lifecycle?
The change in the lifecycle function is due to the adoption of the Fiber architecture, and in the new Fiber architecture, the update of components is divided into two phases:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Render phase: this phase determines which components will be updated.
Commit phase: this is when React starts performing updates (such as inserting, moving, and deleting nodes).
Commit phase executes quickly, but real DOM updates are slow, so React pauses and resumes component updates during updates to avoid blocking browsers for a long time, which means that render phase may be executed multiple times (because it may be interrupted and then re-executed).
Constructor
ComponentWillMount
ComponentWillReceiveProps
ComponentWillUpdate
GetDerivedStateFromProps
ShouldComponentUpdate
Render
These lifecycles belong to render phase,render phase and may be executed multiple times, so avoid introducing side effects into lifecycle functions in render phase. It is easy to introduce side effects in the life cycle before 16.3, so a new life cycle is introduced after 16.3 to limit the introduction of side effects by developers.
GetDerivedStateFromProps (nextProps, prevState)
In React v16.3, static getDerivedStateFromProps is called only in component creation and updates raised by the parent component. If it is not raised by the parent component, then getDerivedStateFromProps will not be called, such as its own setState raise or forceUpdate raise.
This is corrected in React v16.4, where static getDerivedStateFromProps is called before the render method is called, and is called during the initial mount and subsequent updates.
Features:
There are no side effects. Because it is in the render phase of Fiber, it may be executed multiple times. So API is designed as a static function, there is no access to the instance method, and there is no ref to manipulate the DOM, which avoids the possibility of side effects of the instance method. But you can still get method-triggered side effects from props, so think twice before executing functions that may trigger side effects.
Used only to update state. Its only function in this life cycle is to derive a new state from nextProps and prevState. It should return an object to update state, or return null to update nothing.
GetDerivedStateFromProps should be preceded by the static reserved word, declared as a static method, otherwise it will be ignored by react.
The this in getDerivedStateFromProps is undefined.
The static static method can only be called by Class, but the instance cannot be called, so in the React Class component, the static method getDerivedStateFromProps does not have access to the this of the Class instance, that is, this is undefined.
GetSnapshotBeforeUpdate ()
GetSnapshotBeforeUpdate () is called only once, before the most recent render output (submitted to the DOM node), so you can get information about the DOM before this update during this life cycle. Any return value for this life cycle will be passed as the third parameter "snapshot" parameter of componentDidUpdate (), otherwise the third parameter of componentDidUpdate will be undefined.
The value of snapshot (or null) should be returned.
Error handling
When an error is thrown in the constructor of a rendering pass, lifecycle, or subcomponent, the following method is called:
Static getDerivedStateFromError (): this life cycle is called after the descendant component throws an error. It takes the error thrown as a parameter and returns a value to update state
ComponentDidCatch (): this life cycle is called after the descendant component throws an error, and it should be used to log errors and the like.
It receives two parameters:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Error-error thrown.
Info-an object with componentStack key
Life cycle comparison
Pre-16.0 life cycle
Life cycle after 16.0:
Reference:
Analysis of React v16.3 New Lifecycle function
What updates have been made to react 16
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
As a ui library, react transforms the front-end programming from traditional imperative programming to declarative programming, that is, the so-called data-driven view. If you update the real dom directly, such as replacing the generated html with innerHtml directly, it will lead to performance problems such as redrawing and rearrangement. In order to improve performance as much as possible, the React team introduced virtual dom, that is, using js objects to describe the dom tree, and by comparing the virtual objects before and after the two virtual objects to find the smallest dom operation (vdom diff), so as to improve performance.
The reactDom diff mentioned above, before react 16, this process we call stack reconciler, it is a recursive process, when the tree is very deep, a single diff for too long will cause JS threads to continue to be occupied, user interaction response lag, and obvious stutters in page rendering, which is a fatal problem in the modern front end.
So in order to solve this problem, the react team adjusted the entire architecture, introduced the fiber architecture, and replaced the previous stack reconciler with fiber reconciler. Incremental rendering is used. The round robin scheduling algorithm of task priority (expiration) and requestIdleCallback is introduced, which simply divides the previous diff into two stages: the first reconciliation phase of reconciliation and commit; is interruptable and is divided into small tasks (fiber), and do small tasks diff in each detection rendering leisure period. Then there is the commit phase, which is unsplit and uninterruptible, updating the effectTag of the diff node to the page in one breath.
Because reconciliation can be interrupted and there is a problem of task priority, some lifecycle functions before commit, such as componentWillMount, componentWillReceiveProps and componetWillUpdate, will be executed many times, but react has officially announced that these three lifecycle functions will be removed from React17.
Because each call update starts from the root node (RootFiber), for better node reuse and performance optimization. There are always workInprogressTree (future vdom) and oldTree (current vdom) linked lists in react, and the two linked lists refer to each other. This virtually solves another problem, when workInprogressTree generates an error, it does not cause the page rendering to crash, but just fails to update, and the page is still there.
React hooks principle
Before React 16, functional components could not have state management? Because before 16, only class components have corresponding instances, but after 16, the emergence of Fiber architecture, so that each node has the corresponding instance, also has the ability to save state.
The essence of Hooks is closure and two-level linked list.
A closure is a function that has access to variables or methods in the scope of another function. The way to create a closure is to create a closure function within a function, and to access the local variables of the function through the closure function. The closure can break through the characteristics of the action chain domain and transfer the internal variables and methods of the function to the outside.
Hooks linked list
The hooks contained by a component is stored on the memoizedState attribute of the fiber node in the form of a linked list, and the currentHook linked list is the fiber node that is currently being traversed. NextCurrentHook is the new linked list that will be added to the hooks that is traversing the fiber node.
Let currentHook: Hook | null = null; let nextCurrentHook: Hook | null = null Type Hooks = {memoizedState: any, / / points to the current render node Fiber baseState: any, / / initialize initialState, the latest state baseUpdate: Update | null,// currently needs to update the Update. After each update, the last update is assigned to facilitate the react to be on the edge of the rendering error. Data rewind queue: UpdateQueue | null,// allows state to change That is, update next generated by update or dispach: Hook | null, / / link to the next hooks}
State
In fact, state is not unique to hooks, and setState for class operations also exists.
Where does memoizedState,cursor exist? How does it correspond to each function component one by one?
React will generate a component tree (or Fiber single linked list). Each node in the tree corresponds to a component. Hooks data, as information of the component, is stored on these nodes, and the component is born and dies together.
Why can only Hook be called on the outermost layer of the function?
MemoizedState places data in the order defined by hook, and if the hook order changes, memoizedState will not perceive it.
How does a custom Hook affect the functional components that use it?
Share the same memoizedState, share the same order.
How did the "Capture Value" feature come about?
Every time you ReRender, you re-execute the function component, and you don't do anything about the function component that has been executed before.
React setState async update
Principle of setState implementation
SetState implements state updates through a queue mechanism. When setState () is executed, the state that needs to be updated will be shallow merged and put into the status queue, instead of updating the state immediately. The queue mechanism can update state in batches efficiently. If the value of this.state is not modified directly through setState, it will not be placed in the status queue. When the next time setState is called to merge the status queue, the previous modification to this.state will be ignored, resulting in an unpredictable error.
Some synchronous and some asynchronous in setState ()?
In React, if it is event handling raised by React (such as event handling raised by onClick), calling setState will not update this.state synchronously; otherwise, setState calls will execute this.state synchronously.
By "other than that", I mean event handlers that are added directly through addEventListener, bypassing React, and asynchronous calls generated through setTimeout/setInterval.
Reason: in the implementation of the setState function of React, it will determine whether to update this.state directly or put it in the queue based on a variable isBatchingUpdates. IsBatchingUpdates defaults to false, which means that setState will update this.state synchronously. However, there is a function batchedUpdates, which modifies isBatchingUpdates to true, and React calls this batchedUpdates before calling the event handler, resulting in consequences. It is the event handling process controlled by React that setState does not update this.state synchronously.
The "asynchronism" of setState does not mean that it is internally implemented by asynchronous code. In fact, the process and code executed by itself are synchronous, but the calling order of composite events and hook functions is before the update, resulting in the inability to get the updated values immediately in the composite events and hook functions, in the form of the so-called "asynchronous". You can get the updated results through callback in the second parameter setState (partialState, callback).
Call risk
When setState is called, the enqueueSetState method is actually executed, the partialState and _ pendingStateQueue queues are merged, and finally the state update is performed through enqueueUpdate.
PerformUpdateIfNecessary gets _ pendingElement, _ pendingStateQueue, _ pendingForceUpdate, and calls reaciveComponent and updateComponent to update the component.
However, if you call the this.setState method in a shouldComponentUpdate or componentWillUpdate method, it will cause a crash.
This is because when this.setState is called in the shouldComponentUpdate or componentWillUpdate method, the performUpdateIfNecessary method will call the updateComponent method to update the component, while the updateComponent method will call the shouldComponentUpdate and componentWillUpdate methods, resulting in a circular call, causing the browser to crash after running out of memory.
React Fiber
Frame drop: when there are a lot of page elements and need to be refreshed frequently, React 15 will drop frames. The fundamental reason is that a large number of synchronous computing tasks block the browser's UI rendering.
By default, JS operations, page layout, and page rendering all run in the browser's main thread, and they are mutually exclusive.
If the JS operation continues to occupy the main thread, the page will not be updated in a timely manner.
When we call setState to update the page, React iterates through all the nodes of the application, calculates the differences, and then updates the UI. The whole process cannot be interrupted.
If there are many elements on the page, the whole process may take more than 16 milliseconds, and it is easy to drop frames.
How to solve the problem that the main thread is operated by JS for a long time? The JS operation is divided into several steps and completed in batches. After completing some of the tasks, give control back to the browser, giving the browser time to render the page. Wait until the browser is busy before continuing with the previously unfinished tasks.
React 15 and below render recursively, using the JS engine's own function call stack, which executes until the stack is empty.
On the other hand, Fiber implements its own component call stack, which traverses the component tree in the form of a linked list, and can flexibly pause, resume and discard the executed tasks. It is implemented by using the browser's requestIdleCallback
Window.requestIdleCallback () calls functions in turn when the browser is idle, which allows developers to perform background or low-priority tasks in the main event loop without affecting delayed but critical events such as animation and user interaction. Functions are generally executed in the first-in-first-called order, unless the function times out before the browser calls it.
The internal operation of the React framework can be divided into three layers:
The Virtual DOM layer, which describes what the page looks like.
The Reconciler layer is responsible for calling component life cycle methods, performing Diff operations, and so on.
Renderer layer, according to different platforms, render the corresponding pages, the more common are ReactDOM and ReactNative.
Fiber represents the smallest unit of work that can be split in the reconciliation phase, but it actually refers to a linked list tree, which can be represented by a pure JS object:
Const fiber = {stateNode: {}, / / Node instance child: {}, / / Child node sibling: {}, / / sibling node return: {}, / / indicates the target to be merged when the result is returned after processing, usually pointing to the parent node}
Reconciler distinction
The previous Reconciler was named Stack Reconciler. The process of Stack Reconciler operation can not be interrupted, it must go all the way to the dark.
Every time Fiber Reconciler executes, it returns control to the browser, which can be executed in segments.
From Stack Reconciler to Fiber Reconciler, the source code level actually does a recursive change loop.
Scheduling (scheduling)
Scheduling (scheduling) is a process of fiber reconciliation, which mainly assigns tasks to achieve segmented execution. There are six priorities for tasks:
Synchronous, as with previous Stack Reconciler operations, executes synchronously
Task, executed before next tick
Animation, execute before the next frame
High, to be implemented immediately in the near future
Low, it's okay to delay execution a little.
Offscreen, which will only be executed the next render or scroll
High-priority tasks (such as keyboard input) can interrupt the execution of low-priority tasks (such as Diff) and take effect more quickly.
During the execution of Fiber Reconciler, it is divided into two stages:
In stage one, the Fiber tree is generated to get the node information that needs to be updated. This step is a gradual process and can be interrupted.
In phase 2, the nodes that need to be updated will be updated in batches at once, and the process cannot be interrupted.
The interruptible feature of phase one allows higher priority tasks to be executed first, greatly reducing the probability of falling frames on the page at the framework level.
Reference:
Introduction to the principle of React Fiber
React Fiber
The difference between HOC and render props
Render Props: pass in the component to be wrapped as a props property, and then the container component calls this property and passes parameters to it.
Implementation method:
1. Through props.children (props), props.children returns the UI element. Everything in the JSX tag is passed to the RenderProps component as a children prop. Because RenderProps renders {props.children} in a
The subcomponents that are passed will eventually appear in the output.
/ / define const RenderProps = props = > {props.children (props)} / / call {() = > Hello RenderProps}
two。 Define the incoming content by any function in props
/ / define const LoginForm = props = > {const flag = false; const allProps = {flag,... props}; if (flag) {return {props.login (allProps)}} else {return {props.notLogin (allProps)}} / / call LOGIN} noLogin= {() = > NOT LOGIN} / >
Advantages:
1. Support ES6
2. Don't worry about props naming, just take the state you need in the render function
3. No useless components will be generated to deepen the level.
4. The construction of render props schema is dynamic, and all changes are triggered in render, which can make better use of the life cycle of components.
HOC: a function that takes a component as an argument and returns a new component.
Class Home extends React.Component {/ / UI} export default Connect () (Home)
High-level components return a new component each time, which is not conducive to diff and state reuse for react, so the wrapper of high-level components cannot be carried out in the render method, but can only be wrapped when the component is declared as above, which is not conducive to dynamically passing parameters.
Advantages:
1. Support ES6
2. Strong reusability. HOC is a pure function and the returned value is a component, which can be nested in multiple layers.
3. Multiple parameters are supported to enhance the scope of application.
Disadvantages:
1. When multiple HOC are used together, it is impossible to directly judge which HOC is responsible for passing the props of the subcomponent.
2. Multiple components are nested, so it is easy to produce props with the same name.
3. HOC may produce many useless components, deepening the level of components.
Generally speaking, render props is similar to high-level components by adding state to puru component to respond to the life cycle of react.
React communication
The data flow of react is unidirectional, and the most common way is to pass values from the parent component to the child component through props.
Parent-to-child communication: incoming props
The child communicates to the parent: the parent component passes a function to the child component, and then gets the value passed by the child component through the callback of this function
Communication from father to grandson: using context to pass values. React.createContext ()
Brotherly correspondence:
1. Find the same parent component, which can transfer data either by props or by context.
2. Use some global mechanisms to achieve communication, such as redux, etc.
3. Publish and subscribe model
React composition event
The React composite event (SyntheticEvent) is an event object that React simulates all the capabilities of native DOM events, that is, cross-browser wrappers for browser native events.
Why use composite events?
1. Browser compatibility to achieve better cross-platform
React uses a top-level event broker mechanism, which ensures bubbling consistency and can be executed across browsers. The composite events provided by React are used to smooth out the differences between event objects in different browsers and simulate composite events from different platforms.
two。 Avoid garbage collection
Event objects may be created and recycled frequently, so React introduces the event pool to get or release the event object in the event pool. That is, React event objects are not released, but are stored in an array that pops up when the event is triggered, avoiding frequent creation and destruction (garbage collection).
3. Facilitate unified event management and transaction mechanism
Realization principle
In React, "composite events" are bound to the document object as event delegates, and the bound events are automatically destroyed during the component unload (unmount) phase.
Composite events and native events
When the real DOM element triggers the event, it bubbles to the document object and then handles the React event; so the native event is executed first, then the React event is processed, and finally the event mounted on the document is actually executed.
It is best not to mix synthetic events with native events. If the stopPropagation method is executed in the native event, other React events will be invalidated. Because events for all elements will not bubble to the document, all React events will not be registered.
Event pool for synthetic events
Synthetic event object pool is a performance optimization method provided by React event system. Synthetic event objects are managed uniformly in the event pool, and different types of synthetic events have different event pools.
React virtual dom
What is virtual dom?
In React, the result of render execution is not a real DOM node, but a lightweight JavaScript object, which we call virtual DOM. It simulates the nodes in DOM through the Object object of JS, and then renders them into real DOM nodes by specific render methods.
Virtual DOM is one of the highlights of React, with batching (batch processing) and efficient Diff algorithm. Batching collects all the DOM operations and submits them to the real DOM at once. The time complexity of diff algorithm is also reduced from O (n ^ 3) to O (n) of the standard Diff algorithm.
Batching (batch processing)
The main idea is that no matter how many calls setState you make in the React event handler or the synchronous lifecycle method, it will be batched into an update and will eventually be re-rendered only once.
Virtual DOM and Native DOM
If there is no Virtual DOM, you need to manipulate the native DOM directly. When all the data in a large list has changed, it makes sense to reset innerHTML directly, but when only one row of data changes, it also needs to reset the entire innerHTML, which results in a lot of waste.
Redrawing performance consumption for innerHTML and Virtual DOM:
InnerHTML: render html string + recreate all DOM elements
Virtual DOM: render Virtual DOM + diff + necessary DOM updates
Virtual DOM render + diff is obviously slower than rendering html strings, but it is still a pure js-level calculation, which is still much cheaper than the later DOM operations. The total amount of calculation of innerHTML, whether js calculation or DOM operation, is related to the size of the whole interface, but the amount of calculation of Virtual DOM is only related to the size of js calculation and interface size, and the operation of DOM is related to the change of data.
Virtual DOM and MVVM
Compared to React, other MVVM frameworks such as Angular, Knockout, Vue, and Avalon all use data binding. Through the Directive/Binding object, observe the data change and keep the reference to the actual DOM element, and do the corresponding operation when there is a data change. MVVM's change checking is at the data level, while React's checking is at the DOM structural level.
The performance of MVVM also varies according to how change detection is implemented: Angular relies on dirty checking; Knockout/Vue/Avalon uses dependency collection.
Dirty check: scope digest (watcher count)) + necessary DOM updates
Dependency collection: re-collect dependencies (data change) + necessary DOM updates
The most inefficient thing about Angular is that any small change has a performance cost related to the number of watcher, and Angular is more efficient when all the data changes. Dependency collection needs to re-collect dependencies during initialization and data changes, which is almost negligible in small updates, but also consumes when there is a large amount of data.
Performance comparison
When comparing performance, it is necessary to distinguish between different occasions such as initial rendering, small data update, and large data update. Virtual DOM, dirty inspection MVVM and data collection MVVM have different performance and different optimization requirements in different situations.
In order to improve the performance of small data updates, Virtual DOM also needs targeted optimization, such as shouldComponentUpdate or immutable data.
Initial rendering: Virtual DOM > Dirty check > = dependent collection
Small data updates: dependency Collection > Virtual DOM + Optimization > Dirty check (cannot be optimized) > Virtual DOM No Optimization
A large number of data updates: dirty check + optimization > = dependency collection + optimization > Virtual DOM (no / no optimization) > > MVVM no optimization
Diff algorithm
The traditional diff algorithm compares the nodes in turn through cyclic recursion, and the complexity of the algorithm is O (n ^ 3), where n is the total number of nodes in the tree. O (n ^ 3) means that if you want to display 1000 nodes, you have to perform billions of comparisons in turn, which cannot meet the performance requirements of modern front-end.
The diff algorithm mainly includes several steps:
The structure of the DOM tree is represented as a JS object, and then a real DOM tree is constructed based on this object and inserted into the document.
When the state changes, reconstruct a new object tree. Then compare the new tree with the old tree, record the difference between the two trees, and finally apply the recorded difference to the real DOM tree, and update the view.
Diff strategy
React converts the complexity of diff algorithm from O (n ^ 3) to O (n) by formulating a bold diff strategy.
React optimizes the algorithm of tree diff through the strategy of hierarchical difference.
React optimizes the algorithm of component diff through the strategy of generating similar tree structure of the same kind and different tree structure of different kind.
React optimizes the algorithm of element diff by setting the policy of unique key.
Tree diff (hierarchical comparison)
React compares trees hierarchically, and the two trees only compare nodes at the same level.
When it is found that the node no longer exists, the node and its child nodes will be completely deleted without further comparison.
In this way, you only need to traverse the tree once to complete the comparison of the entire DOM tree.
When a node moves across levels, the move operation does not occur, but the tree with the node as the root node is recreated. This is an operation that affects the performance of React, so React officials do not recommend cross-level operation of DOM nodes.
Hierarchical comparison of advanced row tree structure, comparing all child nodes under the same parent node
Let's go on to see what type of node it is. If it's a component, do Component Diff.
If the node is a tag or element, do Element Diff
Note: maintaining a stable DOM structure will help improve performance when developing components. For example, you can hide or show nodes through CSS instead of actually removing or adding DOM nodes.
Component diff (component comparison)
If it is the same type of component, continue to compare virtual DOM tree according to the original policy.
If not, the component is judged to be dirty component, replacing all child nodes under the entire component. For example, when an element changes from
For the same type of component, it is possible that there is no change in its Virtual DOM, which can save a lot of diff computing time if you know this for sure. Therefore, React allows the user to determine whether the component needs to be diff through shouldComponentUpdate ().
For two different types of components that are structurally similar, the structures of the two are not compared and all the contents of the entire component are replaced. There are few opportunities for different types of component to be similar to DOM tree, so it is difficult for this extreme factor to have a significant impact on the implementation development process.
Element diff (element comparison)
When a node is at the same level, React diff provides three node operations: INSERT_MARKUP (insert), MOVE_EXISTING (move), and REMOVE_NODE (delete).
INSERT_MARKUP, the new component type is not in the old collection, that is, it is a new node, and you need to insert the new node.
MOVE_EXISTING, there is a new component type in the old collection, and element is an updatable type, in which case you need to do a move operation, and you can reuse the previous DOM node.
REMOVE_NODE, the old component type, is also available in the new collection, but the corresponding element cannot be directly reused and updated, and delete operation is required, or if the old component is not in the new collection, delete operation is also required.
Duke Villanova Connecticut Duke Villanova
React doesn't realize that Duke and Villanova should be preserved, but rebuilds each child element without moving the DOM.
Key optimization
In order to solve the above problems, React introduces the key attribute to distinguish the same group of child nodes at the same level by adding a unique key.
When a child element has a key, React uses key to match the child elements on the original tree and the child elements on the latest tree. If there are the same nodes, there is no need to delete and create nodes, just move the location of the nodes in the old collection to update the location of the nodes in the new collection.
In the process of development, minimize operations such as moving the last node to the head of the list. When the number of nodes is too large or the update operation is too frequent, the rendering performance of React will be affected to a certain extent.
Key does not need to be globally unique, but it needs to be unique in the list.
Key should be stable, predictable, and unique in the list. Unstable key (such as generated by Math.random ()) can cause many component instances and DOM nodes to be recreated unnecessarily, which can lead to performance degradation and loss of state in subcomponents.
The difference between react and vue
1. The implementation principle of monitoring data change is different.
Vue can accurately know the data changes through the hijacking of getter/setter and some functions.
React is done by default by comparing references (diff), and if not optimized, it may result in a large number of unnecessary re-rendering of VDOM.
two。 Different data streams
Two kinds of bidirectional binding can be implemented in Vue1.0: props can be bidirectionally bound between parent and child components, and bidirectional binding between components and DOM can be achieved through v-model.
There is no two-way binding between parent and child components in Vue2.x (but a syntax sugar is provided to automatically help you modify it through events).
React does not support bidirectional binding and advocates unidirectional data flow, which is called the onChange/setState () pattern.
3. HoC and mixins
The way Vue combines different functions is that the component in mixin,Vue is a wrapped function, not simply the object or function that we pass in when we define the component.
The way React combines different functions is through HoC (high-level components).
4. Different rendering methods of templates
The syntax of the template is different, React renders the template through JSX, and Vue renders through an extended HTML syntax.
The principle of the template is different, React uses native JS to implement the common syntax in the template, such as interpolation, condition, loop and so on. Vue is implemented through instructions, such as v-if, in a separate template separate from the component JS code.
For example, illustrate the benefits of React: the render function in react supports closure features, so our import components can be called directly in render. But in Vue, because the data used in the template must be hung on this for a transfer, we need to declare a component in components after we have finished import.
5. The rendering process is different
Vue can calculate Virtual DOM differences more quickly because it tracks the dependencies of each component and does not need to re-render the entire component tree.
React when the state is changed, all subcomponents are re-rendered. This can be controlled through the lifecycle approach of shouldComponentUpdate, but Vue regards this as the default optimization.
6. The framework is different in nature.
Vue is essentially a MVVM framework, developed from MVC.
React is a front-end component-based framework, developed from the back-end component.
Performance optimization
1. Static resources use CDN
CDN is a group of Web servers distributed in many different geographic locations. The farther away the server is from the user, the higher the latency.
two。 Non-blocking
The inline style and script of the header block the rendering of the page, the style is placed in the header and introduced in link mode, and the script is placed in the tail and loaded asynchronously
3. Compressed file
Compressing files can reduce file download time.
1. In webpack, you can use the following plug-ins for compression:
JavaScript:UglifyPlugin
CSS: MiniCssExtractPlugin
HTML:HtmlWebpackPlugin
two。 Use gzip compression. This function is enabled by adding a gzip identity to the Accept-Encoding header in the HTTP request header.
4. Picture optimization
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Picture lazy load
Responsive images: the browser automatically loads the appropriate pictures according to the screen size.
Reduce picture quality: there are two ways, one is through the webpack plug-in image-webpack-loader, and the other is through the online website for compression.
5. Reduce redrawing and rearrangement
Reduce the complexity of CSS selectors
Use transform and opacity property changes for animation
When modifying a style with JavaScript, it is best not to write the style directly, but to change the style by replacing class.
If you want to perform a series of actions on the DOM element, you can detach the DOM element from the document stream, modify it, and then bring it back to the document. It is recommended to use hidden elements (display:none) or document fragments (DocumentFragement), which can be well implemented.
6. Use requestAnimationFrame to achieve visual changes
Window.requestAnimationFrame () tells the browser that you want to perform an animation and asks the browser to call the specified callback function to update the animation before the next redraw. This method needs to pass in a callback function as an argument, which will be executed before the next redrawing by the browser
7. Webpack package and add file cache
Index.html is set to no-cache so that each request will check whether the index.html file has changed, use the cache if there is no change, and use the new index.html file if there is any change.
All other files use long cache, for example, set to cache one year maxAge: 1000 * 60 * 60 * 24 * 365.
The front-end code is packaged with webpack, and the corresponding file name is generated according to the file content. The file name will change only when the content changes each time.
Max-age: sets the maximum period for cache storage, after which the cache is considered to expire (in seconds). Prior to this time, the browser reading the file does not make a new request, but uses the cache directly.
Specifying no-cache means that the client can cache the resource, and the validity of the cached resource must be reverified each time it is used
What happens after entering url
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
DNS domain name resolution
Establish a TCP connection (three-way handshake)
Send HTTP request
The server processes the request
Return the response result
Close TCP connection (four-way handshake)
Browser parses HTML
Browser layout rendering
1. DNS domain name resolution: get the server ip
After the client receives the domain name address you entered, it first goes to the local hosts file to check whether there is a corresponding domain name and IP correspondence in the file. If so, send a request to its IP address. If not, go to the DNS server.
two。 Establish TCP links: client link server
TCP provides a reliable, connection-oriented, byte streaming, transport layer service. For the TCP link between the client and the server, it is necessary to say "three-way handshake". The function of "three-way handshake" is that both sides can make clear that their receiving and sending ability is normal.
The client sends a data packet with the SYN flag to the server, and after receiving it, the server sends back a data packet with the SYN/ACK flag to convey the confirmation message, and finally the client sends back a data packet with the ACK flag, indicating that the handshake is over and the connection is successful.
SYN-used to initialize the serial number of a connection.
ACK-confirm so that the confirmation number is valid.
RST-resets the connection.
FIN-the sender of this segment has finished sending data to the other party.
Client: "Hello, not at home." -- SYN
Server: "Yes, you come." -- SYN + ACK
Client: "all right." -- ACK
3. Send HTTP request
4. The server processes the request
5. Return the response result
6. Close the TCP connection (4-way handshake required)
In order to avoid the resource consumption and consumption of both the server and the client, when there is no request or response transmission, either party can initiate a shutdown request.
When the connection is closed, when the server receives the FIN message from the other party, it only means that the client no longer sends data but can still receive the data, and the server may not send all the data to the client, so the server can shut down immediately, or send some data to the other party, and then send the FIN message to the other party to indicate that it agrees to close the connection now. Therefore, the ACK and FIN are generally sent separately. Which leads to one more time.
Client: "Brother, I have no data to transmit, let's close the connection." -- FIN + seq
Server: "copy that. I'll see if I have any data." -ACK + seq + ack
Server: "Brother, I have no data to send to you, we can close the connection." -FIN + ACK + seq + ack
Client: "all right." -ACK + seq + ack
7. Browser parses HTML
Browsers need to load and parse not only HTML, but also CSS, JS, and other media resources such as pictures and videos.
The browser parses the HTML, generates the DOM tree, parses the CSS, generates the CSSOM tree, and then generates the rendering tree through the DOM tree and CSSPOM tree. Unlike DOM trees, render trees do not have to display nodes such as head, display for none, and so on.
The parsing process of the browser is not carried out in series. For example, while parsing CSS, you can continue to load parsing HTML, but when parsing executes the JS script, it will stop parsing the subsequent HTML, resulting in blocking problems.
8. Browser render page
According to the render tree layout, the CSS style is calculated, that is, geometric information such as the size and location of each node on the page. HTML is streamed by default, and CSS and js will break this layout and change the appearance style, size and location of the DOM. Finally, the browser draws each node and displays the page to the user.
Replaint: part of the screen is redrawn without affecting the overall layout, for example, the background color of a CSS changes, but the geometric size and position of the elements remain the same.
Reflow: means that the geometric size of the element has changed and the render tree needs to be recalculated.
Reference:
Explain in detail what happened after the browser entered URL
What happens after the browser enters URL?
Front-end routing
What is routing?
Routing is a way to interact with the back-end server, requesting different resources through different paths.
The concept of routing first appeared in the back-end, when the back-end is not separated, the back-end controls the routing, and the server receives the request from the client, parses the corresponding url path, and returns the corresponding page / resource.
Front-end routing
Ajax, whose full name is Asynchronous JavaScript And XML, is a technical solution used by browsers to achieve asynchronous loading.
In the absence of Ajax, most web pages are returned to HTML directly, and each update operation of the user needs to refresh the page and affect the interactive experience. In order to solve this problem, Ajax (Asynchronous loading Scheme) is proposed. With Ajax, the user interaction does not have to refresh the page every time. Then came the SPA single-page application.
User interaction in SPA is achieved by JS changing the HTML content, and the url of the page itself does not change, which leads to two problems:
SPA can't remember the user's operation record, whether it's refresh, forward or backward, it can't show what the user really expects.
Although there are many page display forms in SPA due to different business, there is only one url, which is not friendly to SEO and is not convenient for search engines to include.
Front-end routing is to solve the above problems.
The implementation of Front-end routing
The implementation of front-end routing is actually to detect url changes, intercept url addresses, and parse to match routing rules. There are two ways to do this:
1. Hash mode
Hash refers to the # sign after url and the characters that follow it. The later change in hash value will not cause the browser to send a request to the server. If the browser does not make a request, the page will not be refreshed.
Changes in hash trigger the hashchange event, and you can use the onhashchange event to listen for changes in hash values.
/ / listen for hash changes. Clicking on the forward and backward of the browser will trigger _ window.onhashchange = function () {...} window.addEventListener ('hashchange', function (event) {...}, false)
2.History mode
Before HTML5, browsers already had history objects. But in early history, it could only be used for multi-page redirects:
History.go (- 1); / / back one page history.go (2); / / forward two pages history.forward (); / / forward one page history.back (); / / back one page
In the HTML5 specification, history has added several API:
History.pushState (); / / adds a state history.replaceState () to the history stack of the current browser session; / / modifies the current history entry (not a new one) history.state / / returns a value that represents the state at the top of the history stack
Because history.pushState () and history.replaceState () can change the url without refreshing the page, histroy in HTML5 has the ability to implement front-end routing.
The window object provides an onpopstate event to listen for changes in the history stack, which will be triggered once the history stack information changes.
Calling history.pushState () or history.replaceState () does not trigger the popstate event. This event is triggered only when a browser action is made, such as the _ window.onpopstate event after the execution of history.back () or history.forward ().
/ / History stack change _ window.onpopstate = function () {.}
Note: pushState () does not cause the hashchange event to be called, even if the new URL differs from the previous URL just in terms of anchor data.
Comparison of the two modes
Front-end routing practice
Vue-router/react-router is implemented based on the principle of front-end routing.
There are three forms of history commonly used by react-router:
BrowserHistory: use History API in the browser to process URL. The implementation of history on DOM for browsers that support HTML5 history API.
HashHistory: use the hash (#) section of URL to create a route. Implementation of history on DOM for older browsers.
CreateMemoryHistory: will not be manipulated or read in the address bar, the implementation of history on memory, for testing or non-DOM environments (such as React Native).
The difference between Babel Plugin and preset
Babel is a transcoder, such as converting ES6 to ES5, or JSX to JS, etc. With Babel, developers can use the new JS features in advance.
Original code-- > [Babel Plugin]-- > converted code
Plugin
The core of Babel transcoding is the Babel plug-in (plugin). Babel plug-ins are generally broken down as small as possible, and developers can introduce them as needed, which improves both performance and scalability. For example, for the function of converting ES6 to ES5, Babel has officially broken down 20 + plug-ins. If developers want to experience the arrow function feature of ES6, they only need to introduce the transform-es2015-arrow-functions plug-in instead of loading the ES6 family bucket.
Preset
You can simply think of Babel Preset as a collection of Babel Plugin. If you want to convert all ES6 code to ES5, plug-in-by-plug-in introduction is relatively inefficient, you can use Babel Preset. Babel-preset-es2015, for example, contains all the plug-ins related to ES6 transformations.
Plugin and Preset execution order
Multiple Plugin and Preset can be used at the same time, and the order in which they are executed is important.
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Execute all the Plugin before executing the Preset.
Multiple Plugin, executed in order of declaration.
Multiple Preset, executed in reverse order in declarative order.
For example, if .babelrc is configured as follows, the order of execution is as follows:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Plugin:transform-react-jsx 、 transform-async-to-generator
Preset:es2016 、 es2015
{"presets": ["es2015", "es2016"], "plugins": ["transform-react-jsx", "transform-async-to-generator"]}
How to develop and deploy front-end code
In order to further improve the performance of the website, static resources and dynamic web pages will be deployed in clusters, static resources will be deployed on CDN nodes, and the resources referenced in the web pages will become the corresponding deployment paths. When static resources need to be updated, references in html are also updated.
If the page structure and style are changed at the same time, and the url address corresponding to the static resource is also updated, if you want to release the code now, should you launch the page first or the static resource first?
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Deploy the page first, then the resource: during the interval between the two deployments, if a user visits the page, the old resource will be loaded in the new page structure and cached as the new version. The result is that the user accesses a disordered page, and the page will execute an error until the resource cache expires unless manually refreshed.
First deploy the resource, then deploy the page: within the deployment interval, users with the old version of the resource local cache visit the website. Because the requested page is the old version and the resource reference has not changed, the browser will directly use the local cache. In this case, the page appears normally. However, when users without local cache or expired cache visit the site, the old version of the page will load the new version of resources, resulting in page execution errors, but when the page is deployed, these users will return to normal when they visit the page again.
This bizarre problem originates from the overlay release of resources, which exists when the resources to be released are used to cover the released resources.
It is also easy to solve it, which is to achieve non-overlay publishing. Rename the resource file with the summary information of the file, and put the summary information in the resource file release path, so that the resource with modified content will become a new file published online and will not overwrite the existing resource file.
In the online process, first fully deploy static resources, and then deploy the page in grayscale, the whole problem will be solved perfectly.
The static resource optimization scheme of large companies basically aims to achieve the following things:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Configure ultra-long local cache-save bandwidth and improve performance
Using content summary as the basis for cache update-precise cache control
Static resource CDN deployment-optimizing network requests
Change the resource release path to achieve non-overlay publishing-- smooth upgrade
The addition of large numbers
Function add (a, b) {const maxLength = Math.max (a.length, b.length); a = a.padStart (maxLength, 0); b = b.padStart (maxLength, 0); let t = 0; let f = 0; let sum = ""; for (let I = maxLength-1; I > = 0; iMuk -) {t = parseInt (a [I]) + parseInt (b [I]) + f; f = Math.floor (t / 10) Sum = `${t% 10} ${sum}`;} if (f = 1) {sum = "1" + sum;} return sum;}
Summation of Fibonacci series
Function fib (n) {if (n)
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.