React 组件的生命周期

生命周期(旧)

组件的生命周期可分成三个状态

  • Mounting(挂载):已插入真实 DOM
  • Updating(更新):正在被重新渲染
  • Unmounting(卸载):已移出真实 DOM

挂载阶段:

ReactDOM.render()触发,初次渲染。组件挂载的生命周期调用顺序如下:

  • 1、constructor
  • 2、componentWillMount()
  • 3、render()
  • 4、componentDidMount()

更新阶段:

每当组件的 state 或 props 发生变化时,组件就会更新。

由组件内部this.setState() 或者 父组件render 触发。组件更新的生命周期调用顺序如下:

  • 1、shouldComponentUpdate()
    • 当props或state发生变化的时候,shouldComponentUpdate()会在渲染执行之前被调用。
    • 它是控制组件更新的阀门,默认为true,只能返回true or false。如果为false就不往下走了,无法更新组件。
  • 2、componentWillUpdate()
  • 3、render()
  • 4、componentDidUpdate()

卸载阶段:

由ReactDOM.unmountComponentAtNode()触发。组件卸载的生命周期调用顺序如下:

  • 1、componentWillUnmount(),很常用,经常用来做一些收尾工作

调用forceUpdate(),强制更新:

使用场景:不更改任何state中的数据,强制更新一下。

它与更新阶段的区别:

  • 就是少走一个钩子,就是控制组件更新的阀门的shouldComponentUpdate钩子不走,它不受阀门的控制。

父组件render触发:

componentWillReceiveProps(),可以接收父组件传递过来的props参数,随后走更新阶段


image


生命周期(新)

React16版本之后,以下三个生命周期被废弃

  • componentWillMount()
  • componentWillReceiveProps()
  • componentWillUpdate()

因为这些生命周期容易被误解和滥用。然后,新提出了两个生命周期钩子:

  • getDerivedStateFromProps()
    • 在开发中基本上不用,但是毕竟是新提出来的东西
    • 它要声明为静态的,能接受参数props和state,返回值要是state对象或者null
  • getSnapshotBeforeUpdate()
    • 快照钩子,在更新之前获取快照,此用法并不常见。
    • 它的任何返回值,都会作为参数传给componentDidUpdate

挂载阶段:

  • 1、constructor
  • 2、getDerivedStateFromProps()
    • 在调用render方法之前调用,并且在初始挂载以及后续的更新时都会被调用。
  • 3、render()
  • 4、componentDidMount()

更新阶段:

每当组件的 state 或 props 发生变化时,组件就会更新。

  • 1、getDerivedStateFromProps()
    • 在调用render方法之前调用,并且在初始挂载以及后续的更新时都会被调用。
    • 根据shouldComponentUpdate()的返回值,来判断React组件的输出是否受当前state或者props更改的影响。
  • 2、shouldComponentUpdate()
    • 当props或state发生变化的时候,shouldComponentUpdate()会在渲染执行之前被调用。
    • 它是控制组件更新的阀门,默认为true,只能返回true or false。如果为false就不往下走了,无法更新组件。
  • 3、render()
  • 4、getSnapshotBeforeUpdate()
    • 它的任何返回值,都会作为快照值参数传给componentDidUpdate。
  • 5、componentDidUpdate(preProps, preState, snapShotValue)
    • 它能接受三个参数,一个是preProps、一个是preState,第三个参数就是快照值。
    • preProps和preState就是更新之前的props和state。

卸载阶段:

  • 1、componentWillUnmount(),很常用,经常用来做一些收尾工作

image

posted @ 2022-09-27 11:28  笔下洛璃  阅读(423)  评论(0编辑  收藏  举报