react 生命周期

生命周期函数:到某一时刻组件会自动调用执行的函数。

这里写图片描述

上图的分析:

(1):constructor 是第一个执行的,在里面执行的是初始化,例如stateprops的赋值,可以理解为一个周期函数,是es6语发中自带的一个函数, 不写react组件会自动创建一个空的

(2) : 初始化完以后 mounting 挂载

 componentWillMount   组件第一次即将挂在到页面的时候执行
 render 挂载  
 componentDidMount  组件第一次挂载完成后才会执行

( 3 ) : upDating 更新生命周期 分为:

state更新出发的生命周期函数
props 更新触发的生命周期函数, 比state多一个接受周期的函数

共同的周期
shouldComponentUpdate 在组件更新之前执行,返回一个布尔值,判断到底该不该更新改变的 state 或者props,也接受两个参数nextProps,nextState

应用:

shouldComponentUpdate(nextProps,nextState){
      if(nextProps.list.length !== this.props.list.length){
         return true
      }else{
         return false
      } 
   }

componentWillUpdateshouldComponentUpdate 之后执行,是否执行取决于shouldComponentUpdate 返回是否是true,接受两个参数nextProps, nextState

props 单独的一个周期:
componentWillReceiveProps 在子组件接受到父组件传递的参数,第一次接受到props是不会执行的,只有第二次才会执行,子组件的这个周期就被执行了,有一个参数 props 是传递过来的prop的值

4: unmounting 卸载函数

注意:
新版本注意
componentWillMount
componentWillReceiveProps
componentWillUpdate
由于这个三个生命周期被滥用,在新版本17中会删除这个三个,但是有hack写法,参考文章

所有的周期函数如下:

static getDerivedStateFromProps(nextProps, prevState) {
    4. Updating state based on props
    7. Fetching external data when props change
  }
  constructor() {
    1. Initializing state
  }
  componentWillMount() {
    // 1. Initializing state   这个方法用的挺多,不过最新版就要去掉
    // 2. Fetching external data
    // 3. Adding event listeners (or subscriptions)
  }
  componentDidMount() {
    componentDidMount 组件在挂载之后就会执行  只在第一次执行
    2. Fetching external data
    3. Adding event listeners (or subscriptions)
  }
  componentWillReceiveProps(props) {    //可以接受props 方法
    // 4. Updating state based on props
    // 6. Side effects on props change
    // 7. Fetching external data when props change
  }
  shouldComponentUpdate() {
  }
  componentWillUpdate(nextProps, nextState) {
    // 5. Invoking external callbacks
    // 8. Reading DOM properties before an update

  }
  render() {
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    8. Reading DOM properties before an update
  }
  componentDidUpdate(prevProps, prevState, snapshot) {
    5. Invoking external callbacks
    6. Side effects on props change
  }

  componentWillUnmount() {
  }

其他: 父组件的render函数执行的时候,里面的子组件的render也会跟着发生变化,不管有没有传递数据,有时候会影响性能,因此可以采用生命周期来进行取消这没必要的浪费。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值