React生命周期有哪些?16版本生命周期发生了哪些变化?

目录
文章目录隐藏
  1. 15 生命周期
  2. 16 生命周期

15 生命周期

初始化阶段

  • constructor 构造函数
  • getDefaultProps props默认值
  • getInitialState state默认值

挂载阶段

  • componentWillMount 组件初始化渲染前调用
  • render 组件渲染
  • componentDidMount组件挂载到 DOM 后调用

更新阶段

  • componentWillReceiveProps 组件将要接收新 props前调用
  • shouldComponentUpdate 组件是否需要更新
  • componentWillUpdate 组件更新前调用
  • render 组件渲染
  • componentDidUpdate 组件更新后调用

卸载阶段

  • componentWillUnmount 组件卸载前调用

16 生命周期

初始化阶段

  • constructor 构造函数
  • getDefaultProps props默认值
  • getInitialState state默认值

挂载阶段

  • staticgetDerivedStateFromProps(props,state)
  • render
  • componentDidMount

getDerivedStateFromProps:组件每次被 rerender的时候,包括在组件构建之后(虚拟 dom 之后,实际 dom 挂载之前),每次获取新的 propsstate之后;每次接收新的props之后都会返回一个对象作为新的 state,返回null则说明不需要更新 state;配合 componentDidUpdate,可以覆盖 componentWillReceiveProps的所有用法

更新阶段

  • staticgetDerivedStateFromProps(props,state)
  • shouldComponentUpdate
  • render
  • getSnapshotBeforeUpdate(prevProps,prevState)
  • componentDidUpdate

getSnapshotBeforeUpdate:触发时间: update发生的时候,在 render之后,在组件 dom渲染之前;返回一个值,作为 componentDidUpdate的第三个参数;配合 componentDidUpdate, 可以覆盖 componentWillUpdate的所有用法

卸载阶段

  • componentWillUnmount

错误处理

  • componentDidCatch

React16 新的生命周期弃用了 componentWillMountcomponentWillReceivePorpscomponentWillUpdate新增了 getDerivedStateFromPropsgetSnapshotBeforeUpdate来代替弃用的三个钩子函数。

React16 并没有删除这三个钩子函数,但是不能和新增的钩子函数混用, React17 将会删除这三个钩子函数,新增了对错误的处理( componentDidCatch

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » React生命周期有哪些?16版本生命周期发生了哪些变化?

发表回复