搜索
首页web前端前端问答react的生命周期函数有哪些

react的生命周期函数有:1、componentWillMount函数;2、componentDidMount函数;3、shouldComponentUpdate函数;4、componentWillUpdate函数;5、componentDidUpdate函数;6、componentWillUnmount函数;7、componentWillReceiveProps函数。

react的生命周期函数有哪些

本教程操作环境:Windows10系统、react18.0.0版、Dell G3电脑。

react的生命周期函数有哪些?

react的生命周期函数(超详细)

话不多说,直接进入正题!

先来了解一下react的生命周期函数有哪些:

  • 组件将要挂载时触发的函数:componentWillMount

  • 组件挂载完成时触发的函数:componentDidMount

  • 是否要更新数据时触发的函数:shouldComponentUpdate

  • 将要更新数据时触发的函数:componentWillUpdate

  • 数据更新完成时触发的函数:componentDidUpdate

  • 组件将要销毁时触发的函数:componentWillUnmount

  • 父组件中改变了props传值时触发的函数:componentWillReceiveProps

下面来上代码详细说明一下

一.挂载部分
根据官方生命周期图我们可以看到,一个组件的加载渲染,首先是defaultProps和propsTypes,(这两个是什么下一篇会单独说,这里也不是重点)
然后就是constructor及this.state里的初始数据,所以到这里是第一步。接着就是componentWillMount 组件将要开始挂载了,这是第二步。然后组件挂载,render解析渲染,所以第三步呼之欲出,就是render数据都渲染完成,最后componentDidMount
组件挂载完成。

子组件代码,父组件内引入渲染即可(这里先不上代码)

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

打开控制台查看
7c5e87f620333f13909140187e44f5f.jpg

二.数据更新部分
数据更新的话第一步是shouldComponentUpdate确认是否要更新数据,当这个函数返回的是true的时候才会进行更新,并且这个函数可以声明两个参数nextPropsnextState
nextProps是父组件传给子组件的值,nextState是数据更新之后值,这两个值可以在这个函数中获取到。第二步当确认更新数据之后componentWillUpdate将要更新数据,第三步依旧是render,数据发生改变render重新进行了渲染。第四步是componentDidUpdate数据更新完成

代码的话子组件在上一部分的基础上,在this.state中定义一个初始数据,render中绑定一下这个数据,之后再增加一个按钮声明一个onClick事件去改变这个数据。这样可以看到数据更新部分的效果,我这里把第一部分的代码删掉了,看着不那么乱。

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 onClick={()=>this.setMsg()}>更新msg的数据</button>
			</div>
		) 
	}
}
export default Smzq

8cfa211465eba747fa8b515be46a208.jpg

三.单独说一下componentWillReceiveProps,父组件中改变了props传值时触发的函数
这个函数也就是当我们父组件给子组件传值的时候改变了props的值时触发的函数,刚才在第二部分中也说到shouldComponentUpdate这个函数可以携带两个参数,nextProps就是父组件传给子组件的值
在父组件中定义一个初始title数据,写一个按钮声明一个onClick事件去改变这个title

四.componentWillUnmount组件将要销毁时的函数
在父组件中定义一个flag为true的状态值,添加一个按钮声明一个onClick事件去
更改这个flag实现销毁组件。

父组件代码:

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 className="App">
				{
					this.state.flag?<Smzq title={this.state.title}/>:''
				}
				<button onClick={()=>this.setFlag()}>挂载/销毁生命周期函数组件</button>
				<button onClick={()=>this.setTitle()}>改变app组件的title</button>
	      </div>
	    );
 	}
}
export default App;

子组件完整代码:

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 onClick={()=>this.setMsg()}>更新msg的数据</button>
			</div>
		) 
	}
}
export default Smzq

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

当父组件给子组件传值时
8943677902d0551008e779d8de3ebec.jpg

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

a9fed9a3d85f129770608e4a5a14823.jpg

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

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

推荐学习:《react视频教程

以上是react的生命周期函数有哪些的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
CSS:我可以在同一DOM中使用多个ID吗?CSS:我可以在同一DOM中使用多个ID吗?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

HTML5的目的:创建一个更强大,更容易访问的网络HTML5的目的:创建一个更强大,更容易访问的网络May 14, 2025 am 12:18 AM

html5aimstoenhancewebcapabilities,Makeitmoredynamic,互动,可及可访问。1)ITSupportsMultimediaElementsLikeAnd,消除innewingtheneedtheneedtheneedforplugins.2)SemanticeLelelemeneLementelementsimproveaCceccessibility inmproveAccessibility andcoderabilitile andcoderability.3)emply.3)lighteppoperable popperappoperable -poseive weepivewebappll

HTML5的重要目标:增强网络开发和用户体验HTML5的重要目标:增强网络开发和用户体验May 14, 2025 am 12:18 AM

html5aimstoenhancewebdevelopmentanduserexperiencethroughsemantstructure,多媒体综合和performanceimprovements.1)SemanticeLementLike like,和ImproVereAdiability and ImproVereAdabilityAncccossibility.2)和TagsallowsemplowsemplowseamemelesseamlessallowsemlessemlessemelessmultimedimeDiaiiaemediaiaembedwitWithItWitTplulurugIns.3)

HTML5:安全吗?HTML5:安全吗?May 14, 2025 am 12:15 AM

html5isnotinerysecure,butitsfeaturescanleadtosecurityrisksifmissusedorimproperlyimplempled.1)usethesand andboxattributeIniframestoconoconoconoContoContoContoContoContoconToconToconToconToconToconTedContDedContentContentPrevulnerabilityLikeClickLickLickLickLickLickjAckJackJacking.2)

与较旧的HTML版本相比,HTML5目标与较旧的HTML版本相比,HTML5目标May 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS:使用ID选择器不好吗?CSS:使用ID选择器不好吗?May 13, 2025 am 12:14 AM

使用ID选择器在CSS中并非固有地不好,但应谨慎使用。1)ID选择器适用于唯一元素或JavaScript钩子。2)对于一般样式,应使用类选择器,因为它们更灵活和可维护。通过平衡ID和类的使用,可以实现更robust和efficient的CSS架构。

HTML5:2024年的目标HTML5:2024年的目标May 13, 2025 am 12:13 AM

html5'sgoalsin2024focusonrefinement和optimization,notnewfeatures.1)增强performandemandeffifice throughOptimizedRendering.2)risteccessibilitywithrefinedibilitywithRefineDatientAttributesAndEllements.3)expliencernsandelements.3)explastsecurityConcerns,尤其是withercervion.4)

HTML5试图改进的主要领域是什么?HTML5试图改进的主要领域是什么?May 13, 2025 am 12:12 AM

html5aimedtotoimprovewebdevelopmentInfourKeyAreas:1)多中心供应,2)语义结构,3)formcapabilities.1)offlineandstorageoptions.1)html5intoryements html5introctosements introdements and toctosements and toctosements,简化了inifyingmediaembedingmediabbeddingingandenhangingusexperience.2)newsements.2)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用