React第二篇:组件的生命周期

前言:因为生命周期是必须要掌握的,所以React的第二篇咱就写这。

(版本:16.3.2)

React的生命周期大致分为四个状态:分别是Mouting、Updating、Unmounting、Error handing。以下,让我们来介绍各个状态吧。

(注:不被官网推荐使用的我不会放入实际运行步骤中)


Mouting

创建实例插入Dom的过程状态,将按以下顺序调用这些方法:

  • constructor()
  • static getDerivedStateFromProps() (组建实例化时或props变化会被调用)
  • componentWillMount() / UNSAFE_componentWillMount()
  • render()
  • componentDidMount()

constructor(): 需要初始化state值或bind函数时调用。该方法在类被加载前运行,在用该类时,需要调用super(props),不然props的调用会出错。

static getDerivedStateFromProps(nextprops, prevstate):props变化时被调用,若是父组件重新渲染,也会被调用。它返回新的props值。

componentWillMount():render()前调用的一个函数,现官网不推荐使用。

render():组件的必需品。内容应为相对纯粹的html文,返回null或false时,ReactDOM.findDOMNode(this)将返回null。

componentDidMount():组件装填完毕后,立即被调用。通常DOM节点的初始化都在此,在此方法内调用setState()会调用两次render(),需注意性能。

即若有设置state或bind函数时,整体必会调用的过程为

contructor() -> static getDerivedStateFromProps() -> render() -> componentDidMount()


Updating

通常在props或state值变化时被调用,将按以下顺序调用方法:

  • componentWillReceiveProps() / UNSAFE_componentWillReceiveProps()
  • static getDerivedStateFromProps() (组建实例化时或props变化会被调用)
  • shouldComponentUpdate()
  • componentWillUpdate() / UNSAFE_componentWillUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

componentWillReceiveProps():props变化时被调用,若是父组件重新渲染,也会被调用。setState通常不会调用该方法。现不被推荐使用。

static getDerivedStateFromProps(nextprops,prevstate):props变化时被调用,若是父组件重新渲染,也会被调用。它返回新的props值。

shouldComponentUpdate(nextProps, nextState):在props变化或执行setState时就会被调用,通常情况返回true。若返回false,componentWillUpdate()、render()、componentDidUpdate()将不会被调用。可通过this.props与nextProps或this.state与nextState比较,判断是否返回true,不建议进行深度检查或使用JSON.stringify(),效率会很低。另外以后可能会视为提示而不是严格指令。

componentWillUpdate(nextProps, nextState):渲染之前的一步操作,不能在这调用setState,现不被推荐使用。

render():组件的必需品。内容应为相对纯粹的html文,返回null或false时,ReactDOM.findDOMNode(this)将返回null。

getSnapshotBeforeUpdate(prevProps, prevState):在最近的更改被提交到DOM元素前,使得组件可以在更改之前获得当前值,此生命周期返回的任意值都会传给componentDidUpdate()。

componentDidUpdate(prevProps, prevState, snapshot):更新完成后会立即调用此方法,snapshot的值即为getSnapshotBeforeUpdate的返回值。更新DOM节点的操作可放在这里进行。

即若只有state值变化时,整体必会调用的过程为

shouldComponentUpdate() -> render() -> getSnapshotBeforeUpdate() -> componentDidUpdate()

即若有prop值变化时,整体必会调用的过程为

static getDerivedStateFromProps() -> shouldComponentUpdate() -> render() -> getSnapshotBeforeUpdate() -> componentDidUpdate()


Unmounting

移除DOM节点时,会调用以下方法:

  • componentWillUnmount()

componentWillUnmount():组件销毁之前会被调用。在此需要进行必要的清理,例如使定时器失效等。不能在此调用setState,因为到了这组件永远不能再被渲染。


Error handing

渲染期间,在组件的生命周期内或是构造函数内发生error的话,将调用以下方法:

  • componentDidCatch()

componentDidCatch(error, info):错误边界会抓取组件内JS的错误,并记录显示回退UI。它会捕获渲染期间,生命周期方法以及下面整个树的构造函数的错误。