React生命周期

本文介绍了组件生命周期函数,包括mount挂载、update更新、unmount剔除阶段的相关函数,如componentWillMount、shouldComponentUpdate等。还探讨了父子组件生命周期的执行顺序,指出完成前从根部到子部,完成时从子部到根部,且一套组件执行完再执行下一套。

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

生命周期函数指在某一时刻组件自动执行的函数。
在这里插入图片描述
2.mount挂载
componentWillMount – render – componentDidMount
组件即将被挂载到页面上–挂载–组件被挂载到页面上之后执行
componentWillMount, componentDidMount只会在第一次的时候执行
3.update更新
组件更新有两种情况
1.props发生变化
2.states发生变化
在这里插入图片描述
shouldComponentUpdate在组件被更新之前被执行
(返回true或false来决定组件是否需要被更新)
在这里插入图片描述
componentWillUpdate在组件更新之前,shouldComponentUpdate之后执行, 只有shouldComponentUpdate返回的值是true它才会执行

componentDidlUpdate在组件更新之后执行
比较特殊的componetWillReceiveProps是在组件有接收props参数的情况下它才会执行
1.组件要从父组件接受参数
2.如果这个组件第一次存在于父组件中,不会执行
3.如果这个组件之前已经存在于父组件中,才会执行

4.unmount把组件从页面剔除
componentWillUnmount组件即将被移除的时候执行

父子组件生命周期执行顺序
1、组件生命周期的执行次数是什么样子的???

	只执行一次: constructor、componentWillMount、componentDidMount

  执行多次:render 、子组件的componentWillReceiveProps、componentWillUpdate、componentDidUpdate

  有条件的执行:componentWillUnmount(页面离开,组件销毁时)

  不执行的:根组件(ReactDOM.render在DOM上的组件)的componentWillReceiveProps(因为压根没有父组件给传递props)

2、组件的生命周期执行顺序是什么样子的???
  假设组件嵌套关系是 App里有parent组件,parent组件有child组件。
  在这里插入图片描述
   如果不涉及到setState更新,第一次渲染的顺序如下:
   在这里插入图片描述

 App:   constructor --> componentWillMount -->  render --> 
parent: constructor --> componentWillMount -->  render --> 
child:    constructor --> componentWillMount -->  render  --> 
componentDidMount (child) -->  componentDidMount (parent) --> componentDidMount (App)

这时候触发App的setState事件
在这里插入图片描述

App:   componentWillUpdate --> render --> 
parent: componentWillReceiveProps --> componentWillUpdate --> render --> 
child:    componentWillReceiveProps --> componentWillUpdate --> render -->
componentDidUpdate (child) -->  componentDidUpdate (parent) --> componentDidUpdate (App)

那如果是触发parent的setState呢?
在这里插入图片描述

parent: componentWillUpdate --> render --> 
child:     componentWillReceiveProps --> componentWillUpdate --> render --> 
componentDidUpdate (child) -->  componentDidUpdate (parent) 

那如果是只是触发了child组件自身的setState呢?

在这里插入图片描述

child: componentWillUpdate --> render -->  componentDidUpdate (child)

结论:

1、如图:完成前的顺序是从根部到子部,完成时时从子部到根部。(类似于事件机制)

2、每个组件的红线(包括初次和更新)生命周期时一股脑执行完毕以后再执行低一级别的红线生命周期。
在这里插入图片描述
3、第一级别的组件setState是不能触发其父组件的生命周期更新函数,只能触发更低一级别的生命周期更新函数。

提问:那么这里提一个问题,如果App里面有多个parent1 parent2 …,parent里由多个child,那么生命周期执行顺序应该时什么样的????

结论:一套组件(父包括子,子包括孙)执行的时候一个整体,执行完毕在执行下一套,用到这里就是App里先执行parent1和parent1的子,子的子。。。,然后完毕再执行parent2这一套。

转自:https://www.cnblogs.com/faith3/p/9216165.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值