


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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
