React 生命周期

50 阅读1分钟

React生命周期

React15版本

image.png

组件初始化阶段流程

  • constructor
  • componentWillMount
  • render
  • componentDidMount
  • componentWillUnmount

组件更新阶段流程

  • componentWillRecevieProps
  • shouldComponentUpdate
  • componentWillUpdate
  • render
  • componentDidUpdate
  • conponentWillUnmount

React16版本

image.png

组件初始化阶段

  • constructor
  • getDeriviedStateFormProps
  • render
  • componentDidMount
  • conponentWillUnmount

组件更新阶段

  • getDeriviedStateFromProps
  • shouldComponentUpdate
  • render
  • getSnapshotBeforeUpdate
  • componentDidUpDate
  • componentWillUnmount

生命周期的变动

去除了

  • componentWillReceiveProps
  • componentWillMount
  • componentWillUpdate

getDerivedStateFromProps(nextProps,prevState)

作用:

是为了让 props 能更新到组件内部 state中,它应返回一个对象来更新 state,如果返回 null 则不更新任何内容。

执行时机: 不论创建时还是更新时,都在render之前

特点:

  1. 静态方法,内部的this指向的是类而非实例。所以不能通过this来访问class的属性。要保持其纯函数的特点,通过参数nextProsprevState来进行判断,根据新传入的props来映射state
  2. 没有内容更新的情况下也一定要返回一个null值,不然会报错。
static getDerivedStateFromProps(nextProps,prevState){
    // state无更新时return null
    return null;
}
复制代码