react学习--生命周期

版权声明:本博客为博主原创,转载请注明出处 https://blog.csdn.net/qq_38045106/article/details/84098323

生命周期的重要性,对于学习框架的重要性,就不多说了,下面主要讲一下react的生命周期中的这些钩子函数的基本用法。

话不多说,先上图:

react组件的构造

import React,{ Component } from 'react';//因为编译时要用到React,所以必须要引入

    class Demo extends Component {
      constructor(props,context) {
      super(props,context)//有constructor必须要supper,防止this报错
      this.state = {
          //定义组件的状态state
      }
    }
    componentWillMount () {
    }
    componentDidMount () {
    }
    componentWillReceiveProps (nextProps) {
    }
    shouldComponentUpdate (nextProps,nextState) {//必须要有返回值
    }
    componentWillUpdate (nextProps,nextState) {
    }
    componentDidUpdate (prevProps,prevState) {
    }
    render () {
    return (//最好加上()防止编译时遇到;自动插入的bug
        <div></div>
    )
    }
    componentWillUnmount () {
    }
}
export default Demo;

初始化(挂载)阶段

1.constructor(props,context)

接受父组件传过来的属性,并且可以初始化自己的state,构造器写了就要supper,防止this指向错误。

拓展:(在ES6的类中,每一个类都有一个contructor(构造器),当子类去继承父类的时候,父类的constructor需要执行一下,为子类去继承constructor中的一些东西,如果子类自己没有写constructor,默认的会生成一个constructor并且在其中就会执行弗雷的constructor,执行的方法就是super(),因为子类中的super就是父类的constructor

如果子类自己编写了constructor,那么就需要子类自己去super一次, 否则,子类的this将不被初始化,此时,子类的constructor就可以接收到外界传入的props,但是this上访问不到props,如果在constructor中需要使用到this.props,那么就必须在super中传入props,父类构造器就会为子类的this上挂载props)

2.componentWillMount() 

组件将要挂载

  1. 组件刚刚经过了constructor,数据的初始化完成
  2. 组件没有render,dom还没有渲染

3.render()

插入jxs构成的dom结构(React会生成虚拟dom,然后利用diff算法进行对比,然后将改变的dom进行渲染吗,提高性能),render 函数并不做实际的渲染动作,它只是返回一个JSX描述的结构,最终由React来操作渲染过程,React会渲染render函数return的东西,如果return false  或者 null,就等于告诉React,不渲染任何东西。

4.componentDidMount()

组件已经渲染完成,dom节点生成,组件的数据来源,通常是通过 Ajax 请求从服务器获取,可以使用 componentDidMount 方法设置 Ajax 请求,等到请求成功,再用 this.setState 方法重新渲染 UI,至此,初始化阶段完成

更新(运行中)阶段

1.componentWillReceiveProps(nextprops)

当前组件接受父组件的改变,重新经渲染组件时,接收一个nextprops(对比this.props和nextprops,然后setState当前组件的state,然后进行组件的重新渲染)参数。(nextprops为最新的props)

2.shouldComponentUpdate()

当组件state改变和componentWillReceiveProps(nextprops)后执行,react唯一用于组件重新渲染的生命周期(react中,当父组件的重新渲染会引起子组件的重新渲染,可以在该生命周期中进行判断,如return false  以阻止组件的更新,提高性能)。该生命周期一旦写在代码中,必须返回布尔值,return true或者false,代码才会继续执行,否则会报warning

3.componentWillUpdate()

组件将要重新渲染

4.render()

(上文已将讲过)

5.componentDidUpdate(prevprops,prevstate)

组件更新完成后进入该生命周期,类似于初始化阶段的componentDidMount(componentDidMount只会在第一次初始化完成后进入),参数中prevprops和prevsstate为组件更新前的props和state。

销毁(卸载)阶段

componentWillUnmount()

解除组件中的事件绑定(如onscroll),和一些定时器函数(如setTimeout和setInterval),和vue的销毁阶段类似。

小结:学习过react后,你会感受到react的灵活性,可以和vue对比学习,关于vue的生命周期,可参考我的另一篇博客

https://blog.csdn.net/qq_38045106/article/details/83717141

猜你喜欢

转载自blog.csdn.net/qq_38045106/article/details/84098323