React生命周期函数详细解析

本文深入解析React组件的生命周期,包括初始化阶段的constructor、componentWillMount、render、componentDidMount,以及更新阶段的shouldComponentUpdate、componentWillUpdate、componentDidUpdate。同时,探讨了组件接收新props时的componentWillReceiveProps函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.react生命周期函数
1.constructor --> 01构造函数
2.componentWillMount --> 02组件将要挂载
3.render --> 03数据将要渲染
4.componentDidMount --> 04组件挂载完成

代码
在这里插入图片描述
页面加载完成控制台打印的数据
在这里插入图片描述
5.componentWillUnmount --> 组件销毁的时候触发的生命周期函数
父组件代码(控制子组件代码销毁创建)
在这里插入图片描述
子组件代码
在这里插入图片描述
点击父组件app '挂载和销毁生命周期函数组件’按钮
点击之前
在这里插入图片描述
点击之后
在这里插入图片描述
以上是生命周期函数

二.组件更新数据触发的函数
1.shouldComponentUpdate --> 001是否需要更新数据 return true 需要 return false 不需要
2.componentWillUpdate --> 002组件将要更新数据
3.render -->03数据将要渲染
4.componentDidUpdate -->004组件更新完成数据

代码
在这里插入图片描述
点击 ‘改变数据’ 按钮后效果
在这里插入图片描述
三:ps 父组件改变props传值的时候触发的函数 componentWillReceiveProps
1.父组件代码
在这里插入图片描述
子组件代码
在这里插入图片描述
点击 ‘改变父组件title的值’ 按钮触发
在这里插入图片描述
注意 shouldComponentUpdate(这个也是在组件更新后触发的函数)函数有两个参数
是否需要更新数据 return true 需要 return false 不需要
shouldComponentUpdate(nextProps,nextState){
console.log(‘001shouldComonentUpdata’)
console.log(‘nextProps’,nextProps) //父组件改变后的数据
console.log(‘nextState’,nextState)//子组件改变后的数据
return true
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值