React的生命周期

1,290 阅读3分钟

前言

本文是作为一个前端零基础的小白自学React的一些学习记录,内容主要参考自《深入React技术栈》的内容

1. React的生命周期分类

React组件的生命周期根据广义定义描述,可以分为挂载、渲染和卸载这几个阶段,当渲染后的组件需要更新时,我们会重新去渲染组件,直至卸载,所以,React生命周期又可以分成两类

  • 当组件在挂载或卸载时;
  • 当组件接受新的数据时,即组件更新时; 在这两类情况中,React分别提供了一些生命周期函数供我们掌控组件

2. 组件挂载或卸载过程

2.1 组件的挂载

组件挂载时最基本的过程,这个过程主要做的时组件状态的初始化。挂载是将组件对应的DOM元素生成好之后将其挂到DOM树上的过程

import React, {Component, PropTypes} from 'react';
class App extends Component{
  static PropTypes= {
    // ...
  };
  static defaultProps = {
    // ...
  };
  constructor(props){
    super(props);
    this.state = {
      // ...
    };
  }
  componentWillMount(){
    // ...
  }
  componentDidMount(){
    // ...
  }
  render(){
    return <div>This is a demo</div>
  }
}

其中componentWillMount方法会在render方法之前执行,而componentDidMount方法会在render方法之后执行,分别代表渲染前和渲染后的时刻。

  • 对于componentWillMount而言,该方法在首次渲染之前调用,因此在componentWillMount中执行setState,虽然能改变State的值,但最终的渲染也只是一次
  • 对于componentDidMount而言,如果在其中执行setState方法,组件会再次更新(执行render函数)就相当于组件在初始化时就渲染了两次。

注:componentWillMount和componentDidMount都只是在初始化的时候执行一次(可以理解为只会影响挂载阶段),其它时候这两个生命周期函数不再执行

2.2 组件的卸载

组件的卸载比较简单,只有componentWillUnmount这个生命周期函数可供使用,在componentWillUnmount方法中,我们常常会执行一些清理方法,如时间回收或是清除定时器。

import React, {Component, PropTypes} from 'react';
class App extends Component{
    componentWillUnmount(){
        // ...
    }
    render(){
        return <div>This is a demo</div>
    }
}

3. 数据更新过程

更新过程是指父组件向下传递props或者组件自身执行setState方法时发生的一系列更新动作。

import React, {Component, PropTypes} from 'react';
class App extends Component{
    componentWillReceiveProps(nextProps){
        // ...
    }
    shouldComponentUpdate(nextProps,nextState){
        // ...
    }
    componentWillUpdate(nextProps,nextState){
        // ...
     }
    componentDidUpdate(preProps,prevState){
        // ...
     }
    render(){
      return <div>This is a demo</div>
    }
}

如果组件自身的state更新了,那么会依次执行shouldComponentUpdate、componentWillUpdate、render和componentDidUpdate

3.1 shouldComponentUpdate

shouldComponentUpdate是一个特别的方法,它接受需要更新的props和state,让开发者增加必要的条件判断,让其在需要时更新,不需要时不更新。因此,当方法返回false的时候,组件不再向下执行生命周期方法。shouldComponentUpdate的本质是用来进行正确的组件渲染。

在理想情况下,当父节点props改变的时候,在理想情况下,只需渲染在一条链路上有相关props改变的节点即可。而在默认情况下,React会渲染所有的节点,因为shouldComponentUpdate默认返回true,正确的组件渲染从另一个意义上说,也是性能优化的手段。(此处需要了解虚拟DOM树的diff算法)

3.2 componentWillUpdate和componentDidUpdate

这两个生命周期管理函数对应的是更新过程中渲染前后的时刻,componenntWillUpdate方法需要提供更新的props和state,而componentDidUpdate提供更新前的props和state

3.3 componentWillReceiveProps

如果组件更新是由父组件更新props而更新的,那么在shouldComponentUpdate之前会先执行componentWillReceiveProps方法,此方法可以作为组件接受props之后,渲染组件之前setState的机会