React 组件生命周期

概述

  • 意义:组件生命周期,便于理解组件运行方式,完成更复杂的组件功能,分析组件错误原因
  • 组件生命周期:组件从北创建到挂载到页面运行,再到离开页面组件销毁的过程
  • 钩子函数作用:为开发人员在不同阶段操作组件提供了时机。钩子可以参考 Vue
  • 只有类组件才有生命周期

生命周期说明

挂载阶段

  • 执行时机:组件创建时(页面加载时)
  • 执行属性:
    钩子 函数触发时机作用
    constructor创建组件时,最先执行1. 初始化 state 2. 创建 Ref 等
    render每次组件渲染都会触发渲染 UI(注意: 不能调用 setState()
    componentDidMount组件挂载(完成 DOM 渲染)后1. 发送网络请求 2.DOM 操作

更新阶段

  • 执行时机
    • setState()
    • forceUpdate()
    • 组件接收到新的 props
  • 说明:以上三者任意一种变化,组件就会重新渲染
  • 执行顺序
钩子函数触发时机作用
render每次组件渲染都会触发渲染 UI(与 挂载阶段 是同一个 render)
componentDidUpdate组件更新(完成 DOM 渲染)后DOM 操作,可以获取到更新后的 DOM 内容,不要调用 setState

卸载阶段

  • 执行时机:组件从页面中消失
    钩子函数触发时机作用
    componentWillUnmount组件卸载(从页面中消失)执行清理工作(比如:清理定时器等)

生命周期演示

父组件

import React, { Component } from 'react'
import Child from './Child'

export default class Life extends Component {
  constructor(props) {
    super(props)
    console.log('constructor :>> ', 1)
    // 提供数据
    // 提供ref
    // 绑定 this 指向
    this.state = {
      msg: '123',
      count: 0
    }
    this.inputRef = React.createRef()
  }
  render() {
    console.log('render :>> ', 2)
    // 渲染组件结构
    return (
      <div style={{ color: 'red', background: 'green' }}>
        父级组件
        <button onClick={this.handleClick}>点击事件</button>
        <div>点击次数{this.state.count}</div>
        {this.state.count < 10 && <Child count={this.state.count} />}
      </div>
    )
  }

  handleClick = () => {
    this.setState({
      count: this.state.count + 1
    })
  }

  componentDidMount() {
    console.log('componentDidMount :>> ', 3)
  }
  componentDidUpdate() {
    console.log('componentDidUpdate :>> ', 4)
  }
}

子组件

import React, { Component } from 'react'

export default class Child extends Component {
  // 组件挂载(完成 DOM 渲染)后,可以操作dom,发送请求
  componentDidMount() {
    this.timer = setInterval(() => {
      console.log('object :>> ', 100)
    }, 1000)
  }
  render() {
    return (
      <div>
        <h3>子组件,被点击:{this.props.count}</h3>
      </div>
    )
  }

  // 组件更新(完成 DOM 渲染)后
  componentDidUpdate() {
    console.log('组件更新 :>> ')
  }
  // 组件卸载
  componentWillUnmount() {
    // 销毁定时器
    clearTimeout(this.timer)
  }
}