美文网首页
React生命周期 && 15及16对比

React生命周期 && 15及16对比

作者: 名字一定要够长才可爱 | 来源:发表于2019-11-18 11:58 被阅读0次

15版生命周期

react15.png
初始化阶段
  • constructor 构造函数
  • getDefaultProps props默认值
  • getInitialState state默认值
挂载阶段
  • componentWillMount 组件初始化渲染前调用
  • render 组件渲染
  • componentDidMount 组件挂载到DOM后调用
更新阶段
  • componentWillReceiveProps 组件将要接收新props前调用
  • shouldComponentUpdate 组件是否需要更新
  • componentWillUpdate 组件更新前调用
  • render 组件渲染
  • componentDidUpdate 组件更新后调用
卸载阶段

componentWillUnmount 组件卸载前调用

16版生命周期

react16.png
初始化阶段
  • constructor 构造函数
  • getDefaultProps props默认值
  • getInitialState state默认值
挂载阶段
  • static getDerivedStateFromProps(props,state)

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

  • render 组件渲染
  • componentDidMount 组件挂载到DOM后调用
更新阶段
  • staticgetDerivedStateFromProps(props,state)
  • shouldComponentUpdate 组件是否需要更新
  • render
  • getSnapshotBeforeUpdate(prevProps,prevState)

    被调用于render之后,可以读取但无法使用DOM的时候。它使您的组件可以在可能更改之前从DOM捕获一些信息(例如滚动位置)。此生命周期返回的任何值都将作为参数传递给componentDidUpdate(prevProps,prevState,prevParmas)的第三个参数prevParmas

卸载阶段
  • componentWillUnmount
错误处理
  • componentDidCatch

注意:

  • React16新的生命周期弃用了 componentWillMount、componentWillReceivePorps、componentWillUpdate新增了 getDerivedStateFromProps、getSnapshotBeforeUpdate来代替弃用的三个钩子函数。
  • React16并没有删除这三个钩子函数,但是不能和新增的钩子函数混用, React17将会删除这三个钩子函数,新增了对错误的处理( componentDidCatch)

相关文章

网友评论

      本文标题:React生命周期 && 15及16对比

      本文链接:https://www.haomeiwen.com/subject/jvpquctx.html