react学习-生命周期钩子函数

react使用的越多,就会发现生命周期的参考价值越来越大

  1. componentWillMount: 当前组件的状态和函数加载完毕,页面还没有开始渲染

  2. componentDidMount: 组件视图渲染完毕

  3. shouldComponentUpdate: 状态发生改变时触发,视图是否更新的狗子函数

    有返回值,返回值为true,就会更新视图,执行钩子函数4;返回值为false,就不会更新视图,回到状态2

  4. componentWillUpdate: 视图即将更新

  5. componentDidUpdate: 视图更新完成后执行的钩子函数

  6. componentWillReceiveProps: 父组件传进来的props值发生变化时触发

  7. componentWillUnmount: 视图即将销毁时执行

    // 以下是生命周期组件

    import React from 'react'

    export default class LifeCycleDemo extends React.Component {

     constructor (props) {
       super(props)
       this.state = {
         data: '我是组件状态',
         count: 0
      }
    }

     componentWillMount () {
       console.log('即将渲染视图')
    }

     componentDidMount () {
       console.log('视图渲染完毕')
    }

     shouldComponentUpdate () {
       console.log('状态发生改变的时候触发,决定视图是否更新')
       // return true // 不更新
       return false  // 更新
    }

     componentWillUpdate () {
       // 打印count改变之前的值
       console.log('视图即将更新', this.state.count)
    }

     componentDidUpdate () {
       // 打印count改变之后的值
       console.log('视图更新完成', this.state.count)
    }

     componentWillReceiveProps () {
       console.log('props发生变化时触发')
    }

     componentWillUnmount () {
       console.log('视图即将销毁的时候触发')
    }
     
     // 这里要用箭头函数,否则函数中的this指向为undefined
     changeState = ()=> {
       console.log(this)
       this.setState({
         count: this.state.count + 1
      })
    }

     render () {
       return (
         <div>我是组件
          <h3>{this.state.data}</h3>
          <span>{this.state.count}</span>
          <button onClick={this.changeState}>增加</button>
         </div>
      )
    }
    }

    注意:

    • 一般处理函数是直接放在类里面

    • 钩子函数中的this指向当前组件;但是自定义函数(changeState)中的this指向undefined,要想自定义函数中的this指向当前组件,必须用箭头函数,或者用关键字bind改变函数中this的指向。

posted on 2021-06-20 11:17  妖娆的油条2号  阅读(354)  评论(0编辑  收藏  举报

导航