search
HomeWeb Front-endFront-end Q&AWhat are the life cycle functions of react?

The life cycle functions of react are: 1. componentWillMount function; 2. componentDidMount function; 3. shouldComponentUpdate function; 4. componentWillUpdate function; 5. componentDidUpdate function; 6. componentWillUnmount function; 7. componentWillReceiveProps function.

What are the life cycle functions of react?

The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.

What are the life cycle functions of react?

react’s life cycle function (super detailed)

Without further ado, let’s get straight to the point!

First let’s take a look at the life cycle functions of react:

  • The function that is triggered when the component is about to be mounted: componentWillMount

  • The function that is triggered when the component is mounted: componentDidMount

  • The function that is triggered when the data is to be updated: shouldComponentUpdate

  • #The function that is triggered when the data is about to be updated: componentWillUpdate

  • The function that is triggered when the data update is completed Function: componentDidUpdate

  • Function triggered when the component is about to be destroyed: componentWillUnmount

  • Parent component The function that is triggered when props transfer values ​​has been changed: componentWillReceiveProps

Let’s explain the code in detail

1. Mounting part
According to the official life cycle diagram, we can see that the loading and rendering of a component starts with defaultProps and propsTypes (these two will be discussed separately in the next article, and it is not the focus here)
Then there is constructor and the initial data in this.state, so here is the first step. Then the componentWillMount component is about to start mounting. This is the second step. Then the component is mounted, render parses and renders, so the third step is about to happen, that is, render data is all rendered, and finally componentDidMount
the component is mounted.

Sub-component code, just introduce rendering into the parent component (no code here)

import React ,{Component} from 'react'

class Smzq extends Component{
	constructor(props){
		console.log('01构造函数')		
		super(props)
		this.state={
			
		}
	}
	//组件将要挂载时候触发的生命周期函数
	componentWillMount(){
		console.log('02组件将要挂载')
	}
	//组件挂载完成时候触发的生命周期函数
	componentDidMount(){
		console.log('04组件将要挂载')
	}
	render(){
		console.log('03数据渲染render')
		return(
			<div>
				生命周期函数演示
			</div>
		) 
	}
}
export default Smzq

Open the console to view
What are the life cycle functions of react?

2. Data update part
The first step for data update is shouldComponentUpdate to confirm whether to update the data, only when this function returns true Will be updated, and this function can declare two parameters nextProps and nextState,
nextProps is the value passed from the parent component to the child component, nextState is after the data is updated value, these two values ​​​​can be obtained in this function. In the second step, after confirming the updated data, componentWillUpdate will update the data . The third step is still render. If the data changes, render will be re-rendered. The fourth step is componentDidUpdate data update is completed.

In terms of code, based on the previous part, the subcomponent defines an initial data in this.state, binds this data in render, and then adds a button to declare an onClick event to change this data. In this way, you can see the effect of the data update part. I have deleted the first part of the code here to make it look less messy.

import React ,{Component} from 'react'

class Smzq extends Component{
	constructor(props){
		super(props)
		this.state={
			msg:'我是一个msg数据'
		}
	}
	//是否要更新数据,如果返回true才会更新数据
	shouldComponentUpdate(nextProps,nextState){
		console.log('01是否要更新数据')
		console.log(nextProps)		//父组件传给子组件的值,这里没有会显示空
		console.log(nextState)		//数据更新后的值
		return true;				//返回true,确认更新
	}
	//将要更新数据的时候触发的
	componentWillUpdate(){
		console.log('02组件将要更新')
	}
	//更新数据时候触发的生命周期函数
	componentDidUpdate(){
		console.log('04组件更新完成')
	}
	//更新数据
	setMsg(){
		this.setState({
			msg:'我是改变后的msg数据'
		})
	}
	render(){
		console.log('03数据渲染render')
		return(
			<div>
				{this.state.msg}
				<br>
				<hr>
				<button>this.setMsg()}>更新msg的数据</button>
			</div>
		) 
	}
}
export default Smzq

What are the life cycle functions of react?

3. Let’s talk about componentWillReceiveProps separately. The function that is triggered when the props value is changed in the parent component
This function is when we The function that is triggered when the parent component changes the value of props when passing values ​​to the child component. As mentioned in the second part, the shouldComponentUpdate function can take two parameters. nextProps is the value passed by the parent component to the child component
Define an initial title data in the parent component, write a button to declare an onClick event to change the title

4.componentWillUnmount function when the component is about to be destroyed
Define in the parent component A state value with a flag of true, add a button to declare an onClick event to
change this flag to destroy the component.

Parent component code:

import React, { Component } from 'react';
import Smzq from './components/Smzq'

class App extends Component {
	constructor(props){
		super(props)
		this.state={
			flag:true,
			title:"我是app组件的标题"
		}
	}
	//创建/销毁组件
	setFlag(){
		this.setState({
			flag:!this.state.flag
		})
	}
	//改变title
	setTitle(){
		this.setState({
			title:'我是app组件改变后的title'
		})
	}
  	render() {
	    return (
	      <div>
				{
					this.state.flag?<smzq></smzq>:''
				}
				<button>this.setFlag()}>挂载/销毁生命周期函数组件</button>
				<button>this.setTitle()}>改变app组件的title</button>
	      </div>
	    );
 	}
}
export default App;

Full code of child component:

import React ,{Component} from 'react'

class Smzq extends Component{
	constructor(props){
		super(props)
		this.state={
			msg:'我是一个msg数据'
		}
	}
	//组件将要挂载时候触发的生命周期函数
	componentWillMount(){
		console.log('02组件将要挂载')
	}
	//组件挂载完成时候触发的生命周期函数
	componentDidMount(){
		//Dom操作,请求数据放在这个里面
		console.log('04组件挂载完成')
	}
	//是否要更新数据,如果返回true才会更新数据
	shouldComponentUpdate(nextProps,nextState){
		console.log('01是否要更新数据')
		console.log(nextProps)		//父组件传给子组件的值,这里没有会显示空
		console.log(nextState)		//数据更新后的值
		return true;				//返回true,确认更新
	}
	//将要更新数据的时候触发的
	componentWillUpdate(){
		console.log('02组件将要更新')
	}
	//更新数据时候触发的生命周期函数
	componentDidUpdate(){
		console.log('04组件更新完成')
	}
	//你在父组件里面改变props传值的时候触发的函数
	componentWillReceiveProps(){
		console.log('父子组件传值,父组件里面改变了props的值触发的方法')
	}
	setMsg(){
		this.setState({
			msg:'我是改变后的msg数据'
		})
	}
	//组件将要销毁的时候触发的生命周期函数,用在组件销毁的时候执行操作
	componentWillUnmount(){
		console.log('组件销毁了')
	}
	render(){
		console.log('03数据渲染render')
		return(
			<div>
				生命周期函数演示--{this.state.msg}--{this.props.title}
				<br>
				<hr>
				<button>this.setMsg()}>更新msg的数据</button>
			</div>
		) 
	}
}
export default Smzq

点击挂载/销毁生命周期函数组件这个按钮的时候
子组件消失,控制台打印:组件销毁了。

当父组件给子组件传值时
What are the life cycle functions of react?

这里nextProps这个就有上图划红线的值了。
那么我们再点击改变app组件的title这个按钮

What are the life cycle functions of react?

这里可以看到componentWillReceiveProps这个函数被触发了,nextProps这个值也发生了改变。

到这里就全部结束了,可能写的不够清晰,不知道有没有人能看完,over。

推荐学习:《react视频教程

The above is the detailed content of What are the life cycle functions of react?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

React: A Powerful Tool for Building UI ComponentsReact: A Powerful Tool for Building UI ComponentsApr 19, 2025 am 12:22 AM

React is a JavaScript library for building user interfaces. Its core idea is to build UI through componentization. 1. Components are the basic unit of React, encapsulating UI logic and styles. 2. Virtual DOM and state management are the key to component work, and state is updated through setState. 3. The life cycle includes three stages: mount, update and uninstall. The performance can be optimized using reasonably. 4. Use useState and ContextAPI to manage state, improve component reusability and global state management. 5. Common errors include improper status updates and performance issues, which can be debugged through ReactDevTools. 6. Performance optimization suggestions include using memo, avoiding unnecessary re-rendering, and using us

Using React with HTML: Rendering Components and DataUsing React with HTML: Rendering Components and DataApr 19, 2025 am 12:19 AM

Using HTML to render components and data in React can be achieved through the following steps: Using JSX syntax: React uses JSX syntax to embed HTML structures into JavaScript code, and operates the DOM after compilation. Components are combined with HTML: React components pass data through props and dynamically generate HTML content, such as. Data flow management: React's data flow is one-way, passed from the parent component to the child component, ensuring that the data flow is controllable, such as App components passing name to Greeting. Basic usage example: Use map function to render a list, you need to add a key attribute, such as rendering a fruit list. Advanced usage example: Use the useState hook to manage state and implement dynamics

React's Purpose: Building Single-Page Applications (SPAs)React's Purpose: Building Single-Page Applications (SPAs)Apr 19, 2025 am 12:06 AM

React is the preferred tool for building single-page applications (SPAs) because it provides efficient and flexible ways to build user interfaces. 1) Component development: Split complex UI into independent and reusable parts to improve maintainability and reusability. 2) Virtual DOM: Optimize rendering performance by comparing the differences between virtual DOM and actual DOM. 3) State management: manage data flow through state and attributes to ensure data consistency and predictability.

React: The Power of a JavaScript Library for Web DevelopmentReact: The Power of a JavaScript Library for Web DevelopmentApr 18, 2025 am 12:25 AM

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

React's Ecosystem: Libraries, Tools, and Best PracticesReact's Ecosystem: Libraries, Tools, and Best PracticesApr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

React and Frontend Development: A Comprehensive OverviewReact and Frontend Development: A Comprehensive OverviewApr 18, 2025 am 12:23 AM

React is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.