简述React的生命周期

本文详细介绍了React组件的生命周期,包括初始化、更新、卸载和错误处理四个阶段的主要生命周期方法,如constructor、getDerivedStateFromProps、componentDidMount、shouldComponentUpdate、componentDidUpdate和componentWillUnmount等。并强调了各个阶段的适用场景和最佳实践,如数据请求、DOM操作和性能优化。
摘要由CSDN通过智能技术生成

React的生命周期

React中组件有生命周期,也就是说也有很多钩子函数供我们使用, 组件的生命周期,我们会分为四个阶段,初始化、运行中、销毁、错误处理(16.3之后)

初始化

在组件初始化阶段会执行

  1. constructor (用来定义状态,或者是用来放一些this的方法的)
  2. static getDerivedStateFromProps() ----将来会使用(定义一个状态,这个状态将来会使用)
  3. componentWillMount() / UNSAFE_componentWillMount() ----带有 UNSAFE属于过时的钩子函数(老版本的)
    componentWillMount()会在17版本后启用,使用static getDerivedStateFromProps()
  4. render()
  5. componentDidMount()(组件挂载结束)

更新阶段
props或state的改变可能会引起组件的更新,组件重新渲染的过程中会调用以下方法:

  1. componentWillReceiveProps() / UNSAFE_componentWillReceiveProps() (属性发生改变)
  2. static getDerivedStateFromProps()(属性发生改变触发)
  3. shouldComponentUpdate() // react性能优化第二方案 (组件应该更新么)
  4. componentWillUpdate() / UNSAFE_componentWillUpdate()
  5. render()
  6. getSnapshotBeforeUpdate() (快照)
  7. componentDidUpdate()(组件更新结束)

卸载阶段
1. componentWillUnmount()

错误处理
1. componentDidCatch() --16.3版本之后出现的

各生命周期详解

1.constructor(props)

通过super来继承父类身上传递过来的属性,然后当前组件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值