React 生命周期

React 生命周期

 

生命周期详述

  1. 组件的三个生命周期状态:

    * Mount:插入真实 DOM

    * Update:被重新渲染

    * Unmount:被移出真实 DOM

  1. React 为每个状态都提供了勾子(hook)函数

    * componentWillMount()

    * componentDidMount()

    * componentWillUpdate()

    * componentDidUpdate()

    * componentWillUnmount()

  1. 生命周期流程:
    1. 第一次初始化渲染显示: ReactDOM.render()

      * constructor(): 创建对象初始化state

      * componentWillMount() : 将要插入回调

      * render() : 用于插入虚拟DOM回调

      * componentDidMount() : 已经插入回调

    1. 每次更新state: this.setSate()

      * componentWillUpdate() : 将要更新回调

      * render() : 更新(重新渲染)

      * componentDidUpdate() : 已经更新回调

    1. 移除组件: ReactDOM.unmountComponentAtNode(containerDom)

      * componentWillUnmount() : 组件将要被移除回调

重要的勾子

  1. render(): 初始化渲染或更新渲染调用
  2. componentDidMount(): 开启监听, 发送ajax请求
  3. componentWillUnmount(): 做一些收尾工作, 如: 清理定时器
  4. componentWillReceiveProps(): 后面需要时讲