A brief analysis of the life cycle of React components (code analysis)
This article brings you a brief analysis of the life cycle (code analysis) of React components. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The entire React life cycle has three stages: creation, update, and uninstall. Each stage has corresponding work and methods. We can study it by looking at the following classic diagram:
The first stage
This is the stage of virtual DOM creation. Five methods will be executed in sequence. Among these five methods, except the render method, the other four methods It is only called once in the entire life cycle, and it will definitely be called once:
getDefaultProps()
This method is created when the component instance is created Before, that is, before the constructor is executed, get the parameters passed by the parent component. You can edit the parameters here and return the new parameters as props
getInitalState()
When the component is created, this method will be called to initialize the state of the component
componentWillMount()
In the component This method is executed before render and can be used to modify state. React first calls this function of the parent component, and then calls this function of the child component
render()
Start the component rendering function and return a A virtual DOM with only one root node. The component's state cannot be modified synchronously in this function.
componentDidMount()
After render rendering, notify that the component has been loaded. React first calls this function of the child component, and then calls this function of the parent component. Starting from this function, the component can interact with other frameworks. For example, setting a timer or making a network request.
Second stage
At this time, the component has entered the stable operation stage. At this stage, the component can handle user interaction or receive events to update the interface. The following methods can be executed many times during the entire life cycle, or not executed once.
componentWillReceiveProps()
This function of the child component will be called when the corresponding parameters in the parent container change. New props will be passed in as parameters, and old props can be obtained based on this.props. We can do some processing on state in this function. And updating the state in this function will not cause secondary rendering
shouldComponentUpdate()
This function passes two parameters, the new state and new props. Changes in state and props will be called to this function. This function mainly makes judgments on the passed nextProps and nextState. If it returns true, it will be re-rendered (default is true), if it returns false, it will not be re-rendered. Under certain conditions, we can choose to update or not update based on the passed props and state, thereby improving efficiency.
componentWillUpdate()
Similar to the componentWillMount method, it is called before render. The component will receive new props or state. After this function is called, nextProps and nextState will be set to this.props and this.state respectively.
componentDidUpdate()
Similar to the componentDidMount method, it is called after render is rendered and this function is called after the real DOM is generated. The parameters passed are the previous props and state.
The third stage
This is the death stage, which mainly cleans and releases memory. There is only one method at this stage, which is called only once during the entire life cycle.
componentWillUnmount()
When the component is to be removed from the interface, componentWillUnmount will be called. Some related destruction operations are performed here, such as canceling timers, event monitoring, etc.
Several situations that trigger render
Here we only consider shouldComponentUpdate has not been modified, and always returns true
First rendering, that is, Initial Render
Call this.setState (it will not be triggered every time setState is called, react will optimize, such as the input component of antd)
The parent component occurs Update, usually the modified props of the child component
If the parent component triggers render, the child component will of course trigger the render
call accordingly this.forceUpdate()
A simple example
import React from 'react'; import ReactDOM from 'react-dom'; import style from './font.css'; import './index.less'; class Parent extends React.Component{ constructor(props) { super(props); this.state = { willRender: true, prop: 1 }; } render(){ return ( <div> <button>{this.setState({prop: 10})}}>changePropsFromParent</button> { this.state.willRender && <child></child> } <button>{this.setState({willRender: false})}}>UnmountChild</button> </div> ); } } class Child extends React.Component { constructor(props) { super(props); this.state = { curr: 0 }; } getDefaultProps(){ console.log('getDefaultProps'); } getInitalState(){ console.log('getInitalState'); } componentWillMount(){ console.log('componentWillMount'); } componentDidMount(){ console.log('componentDidMount'); } componentWillReceiveProps(){ console.log('componentWillReceiveProps'); } shouldComponentUpdate(){ console.log('shouldComponentUpdate'); return true; } componentWillUpdate(){ console.log('componentWillUpdate'); } componentDidUpdate(){ console.log('componentDidUpdate'); } componentWillUnmount(){ console.log('componentWillUnmount'); } render() { console.log('render') return ( <div> <button>this.setState({curr:2})}>setState</button> <button>{this.forceUpdate();}}>forceUpdate</button> </div> ); } } ReactDOM.render( <parent></parent>, document.getElementById('root') );
Related recommendations:
React component life cycle instance analysis
How long is the life cycle of React Native components
The above is the detailed content of A brief analysis of the life cycle of React components (code analysis). For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.