React - 组件的生命周期

一. 旧版本生命周期

  • constructor(props) :构造器 完成了React数据的初始化
  • componentWillMount :组件将要挂载的钩子
  • componentDidMount :组件挂载完毕的钩子
  • componentWillReceiveProp(props) :组件将要接收组件新的props的钩子
  • shouldComponentUpdate :控制组件是否继续更新
    必须返回值 true/false,返回值默认为 true。
  • componentWillUpdate :组件将要更新的钩子
  • componentDidUpdate :组件更新完成的钩子
  • render :页面渲染
  • componentWillUnmount :销毁组件之前的钩子

各阶段生命周期执行顺序:

  1. 初始化阶段,挂载时
    constructor => componentWillMount => render => componentDidMount
  2. 更新阶段
    componentWillReceiveProps => shouldComponentUpdate => componentWillUpdate => render => componentDidUpdate
  3. 销毁组件
    componentWillUnmount

二. 新版本生命周期

  • constructor(props) :构造器 完成了React数据的初始化。
  • getDerivedStateFromProps(props, state) :若 state 的值在任何时候都取决于 props,那么可以使用 getDerivedStateFromProps。
    使用时需加static修饰符,如: static getDerivedStateFromProps(props, state)
    应返回一个对象来更新 state,如果返回 null 则不更新任何内容。
  • shouldComponentUpdate :控制组件是否继续更新
    必须返回值 true/false,返回值默认为 true。
  • render :页面渲染。
  • componentDidMount :组件挂载完毕的钩子。
  • getSnapshotBeforeUpdate :最近更新渲染(提交到 DOM 节点)之前调用。
    应返回 snapshot 的值(或 null)。
  • componentDidUpdate(prevProps, prevState, snapshotValue) :组件更新完成的钩子。
  • componentWillUnmount :销毁组件之前的钩子。

各阶段生命周期执行顺序:

  1. 初始化阶段,挂载时
    constructor => getDerivedStateFromProps(props, state) => render => componentDidMount
  2. 更新阶段
    getDerivedStateFromProps(props, state) => shouldComponentUpdate => render => getSnapshotBeforeUpdate => componentDidUpdate
  3. 销毁组件
    componentWillUnmount

三. 新旧生命周期对比

  1. 废弃三个生命周期钩子
    componentWillMount
    componentWillReceiveProps
    componentWillUpdate
  2. 新增两个生命周期钩子
    getDerivedStateFromProps
    getSnapshotBeforeUpdate
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值