React组件的生命周期理解

React组件的生命周期(理解)

React组件在网页中会经历创建、更新、删除三个过程。其生命周期也会历经三个过程:

  1. 装载过程(Mount)组件第一次在DOM中渲染。
  2. 更新过程(Update)组件重新渲染。
  3. 卸载过程(Unmount)组件在DOM中删除。
装载过程:

装载过程是组件第一次在DOM中渲染的过程,会依次调用如下函数:

  1. constructor
  2. getInitialState
  3. getDefaultProps
  4. componentWillMount
  5. render
  6. componentDidMount
constructor:

constructor函数是组件的构造函数,主要功能为:
    1. 初始化state
    2. 绑定函数的this环境(也可不进行绑定,函数使用ES6中的箭头函数即可绑定this到当前组件实例)

getInitialState && getDefaultProps:

1.getInitialState和getDefaultProps函数在ES6的React组件中不会用到,一个是设置初始状态,一个是设置默认属性。

componentWillMount:

componentWillMount也基本不会用到,componentWillMount发生在即将装载时,即使重新setState也已经迟了,不会引起重绘,所以componentWillMount的内容完全可以放在constructor中执行。

render:

render函数为纯函数,不可以在render函数中改变组件的props和state。组件中一定要有render函数,因为其他函数都有默认实现,而render函数没有。如果组件不需要渲染界面,则在render中返回null或者false即可。

componentDidMount:

当render函数返回的东西已经发生渲染后,会触发componentDidMount函数。该函数是经常使用的函数。

更新过程:

更新过程就是组件的props或者state改变时触发组件的更新。依次调用如下函数:

  1. componentWillReceiveProps
  2. shouldComponentUpdate
  3. componentWillUpdate
  4. render
  5. componentDidUpdate
componentWillReceiveProps(nextProps):

只要父组件的render函数被调用,在其render函数中的子组件就会触发componentWillReceiveProps函数。

shouldComponentUpdate(nextProps, nextState):

规定什么时候需要重新渲染,用于提高React组件性能。

componentWillUpdate、componentDidUpdate:

类似于componentWillMount和componentDidMount,一个在render前,一个在render后。

卸载过程:

卸载过程只涉及一个函数:
componentWillUnmount
因为卸载组件后不需要再对组件有任何操作,所以只需要componentWillUnmount函数对组件删除之前进行一些操作即可。

整体流程图:


新的生命周期加入了static getDerivedStateFromProps (nextProps, prevState)和getSnapshotBeforeUpdate (prevProps, prevState)这两个钩子函数用来代替componentWillReceiveProps以及componentWillUpdate,也删除了componentWillMount。

static getDerivedStateFromProps (nextProps, prevState)可以直接return相应的state,以更新当前的state,如果没有状态更新,则return null.

getSnapshotBeforeUpdate (prevProps, prevState)发生在React更新Dom元素之前,获取一个快照,它返回的结果将作为componentDidUpdate(prevProps, prevState,snapShot)的第三个参数,可根据第三个参数的值在componentDidUpdate生命周期中进行状态更新。

同时,加入了错误捕获处理钩子函数componentDidCatch用来捕获错误。


参考文献: React官方教程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值