tk挠痒痒网址发布页-秘密武器
历史搜索

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

游客2025-05-16 11:43:02
目录文章目录
  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

本文是由用户"游客"发布,所有内容的版权归原作者所有。没有经过书面许可,任何单位或个人不得以任何形式复制、转载、引用本网站的内容。否则将追究法律责任。

相关专题