React 组件生命周期

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

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


Mounting 挂载阶段

Mounting阶段叫挂载阶段,伴随整个虚拟DOM的声明。它里面有四个小的生命周期函数,分别是:

  1. constructor:初始化属性
  2. componentWillMount:在组件即将被挂载到页面的时候执行
  3. render:页面state或props发生变化时执行
  4. componentDidMount`:组件挂载完成之后执行

以下我们可以写一些代码来验证以下这四个阶段的执行顺序:

import React, { Component } from 'react'

export default class classs extends Component {
    // 挂载阶段 
    constructor(props){
      super(props)
      console.log('1.constructor(props) --------- 组件初始化')
    }
    // 挂在前
    componentWillMount() {
        console.log('2.componentWillMount --------- 组件挂载之前')
    }
    // 挂在中
    render() {
      console.log('3.render -------- 组件中')
      return (
        <div>测试组件生命周期</div>
      )
    }
    // 挂在后(常用)
    componentDidMount() {
        console.log('4.componentDidMount --------- 组件挂载之后')
    }
}

注意:componentWillMount 和 componentDidMount 这两个生命周期函数,只在页面刷新时执行一次,而 render 函数只要有state和props变化就要执行


Updation更新阶段

Updation会在组件发生改变的时候执行。

  1. shouldComponentUpdate:该函数会在组件更新之前,自动被执行。
  2. componentWillUpdate:该函数在组件更新之前,但shouldComponentUpdate之后被执行,如果shouldComponentUpdate返回false,那么该函数就不会被执行。
  3. componentDidUpdate:该函数在组件更新之后执行,它是组件更新的最后一个环节。

 以下我们可以写一些代码来验证以下这三个阶段的执行顺序:

shouldComponentUpdate() {
  console.log('5.shouldComponentUpdate ------- 组件更新之前')
  return true
}
componentWillUpdate() {
   console.log('6.componentWillUpdate --------- 组件更新之前,shouldComponentUpdate函数后')
}
componentDidUpdate() {
  console.log('7.componentDidUpdate --------- 组件更新之后')
}

Unmounting 卸载阶段

componentWillUnmount:组件在卸载阶段时执行。

// 页面卸载时执行
componentWillUnmount() {
  console.log('componentWillUnmount ----------- child')
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值