《深入React技术栈》个人总结之1.5React生命周期(打卡四)

本文深入解析React组件的生命周期,包括挂载、渲染、更新和卸载等关键阶段,阐述了不同生命周期函数的作用与应用场景,如constructor、componentWillMount、componentDidMount、shouldComponentUpdate、componentWillReceiveProps等。

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

因此,React组件分为两大类:

  • 当组件在挂载或卸载时
  • 当组件接收新的数据时,即组件更新时。

React生命周期函数:

    组件加载的时候触发的周期函数

      constructor  数据初始化

     componentWillMount  组件将要挂载的时候触发的生命周期函数

     componentDidMount   组件挂载完成的时候触发的生命周期函数 (对DOM操作,ajax操作)        

    组件数据更新的时候触发的生命周期函数

   shouldComponentUpdate  //是否更新数据   return true  两个参数(nextProps, nextState)

   componentWillUpdate 将要更新数据的时候触发

   render   

   componentDidUpdate  组件数据更新完成的时候

    你在父组件里面改变props传值的时候触发的函数

   componentWillReceiveProps

    组件销毁的时候触发的:

  componentWillUnMount  //用在组件销毁的时候执行的操作

 

理论太枯燥了,这里我自己用code来理解一下,组件的生命周期过程吧

import React,{ Component } from 'react'

export default class Demo extends Component {
  static propTypes = {
    // props类型检查
  }
  static defaultProps = {
    // 默认类型
  }
  // propTypes和defaultProps被声明成静态属性,意味着从类外面也可以访问他们如:App.propTypes和App.defaultProps
  constructor(props) {
    super(props);
    this.state = {
      
    }
  }
  componentWillMount() {
    // 组件渲染之前(初始化,且执行一次)
  }
  componentDidMount() {
    // 组件渲染之后(在render函数执行之后,执行)
    // ajax
  }

  componentWillUnmount() {
    // 组件卸载之前
    // 这里我们常常执行一些清理方法,如事件回收或者是清理定时器
  }

  // 数据更新过程
  // 更新过程指的是父组件向下传递props或组件自身执行setState方法时发生的一系列更新动作
  shouldComponentUpdate(nextProps, nextState) {
    // 接受需要更新的props和state,让开发者增加必要的条件判断,让其在需要的时候更新,不需要则不更新。
    // 默认返回true,当方法返回false时组件不再向下执行生命周期方法
    // 在这里提下无状态组件,它是没有生命周期的,意味着没有shouldComponentUpdate 可以使用class App extends PureComponent 来优化组件
    // return true

  }
  componentWillUpdate(nextProps, nextState) {

  }
  componentDidUpdate(nextProps, nextState) {

  }

  render() {
    return (
      <div>this is a demo</div>
    )
  }
}

es6 classes与createClass构建组件方法的不同

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值