react的生命周期

当组件第一次渲染的时候执行哪些生命周期?

constructor--->componentWillMount--->render--->componentDidMount

1.constructor

初始化

当前生命值周期可以定义当前组件所需要的状态

当前生命周期函数必须写super,否则就会报错或者this的指向发生改变

如果在super和constructor中没有传递props这个参数的话是访问不到this.props属性的

2.componentWillMount

组件挂载前

在当前生命周期函数里可以访问到props属性,在这里可以接收外部属性,同时可以将外部属性转变成内部属性

在当前生命周期函数里不需要调用setState,因为当前函数执行完毕后会自动执行render

3.render

a.render函数什么时候会执行?

当this.state,this.props发生改变的时候,会执行render函数

b.this.state/this.props发生改变的时候会执行哪些生命周期函数

  this.state:

    shouldComponentUpdate--->componentWillUpdate--->render--->componentDidUpdate

  this.props

    componentWillReveiceProps--->shouldComponentUpdate--->componentWillUpdate--->render--->componentDidUpdate

c.render函数执行的时候会将虚拟DOM和数据相结合,缓存一份虚拟DOM,当数据发生改变的时候会将虚拟DOM与缓存的虚拟DOM作比较(diff算法),比较完毕以后,将需要修改的虚拟DOM进行批量修改,减少不必要的更新。

d.diff算法

新旧两个虚拟DOM的对比就是diff算法

4.componentDidMount

render函数执行后,componentDidMount这个生命周期函数就会执行,在这个生命周期函数里可以进行fatch请求,获取真实DOM

5.componentWillUnMount

组件销毁

6.shouldComponentUpdate

当this.state,this.props发生改变时,会执行render函数

该生命周期函数必须返回一个布尔值,如果返回true,则继续执行下面的生命周期函数;

                 如果返回false,则下面的生命周期函数不执行。

该生命周期函数是用来判断DOM是否更新的,而不是用来判断数据是否更新的(不管返回值是true还是false,this.state里的数据都会改变,但是DOM值不会改变)

该生命周期函数可以做一些相关操作减少虚拟DOM不必要的更新(利用接收到的两个参数props,state来比较)

7.componentWillUpdate

更新前  虚拟DOM与数据相结合,但没有真正的DOM结构

8.componentDidUpdate

更新后  数据与模板结合可以产生真正的DOM结构,在这里可以获取到数据更新后最新的DOM结构

9.componentWillReceiveProps

当外部属性发生变化的时候就会执行当前生命周期函数,当前生命周期函数会有一个新的参数props

操作DOM的两种方式:

 ref="list"      this.refs.list

 ref={(tagName)=>{this.key=tagName}}   this.key

react生命周期函数哪些只执行一次?

constructor 

componentWillMount

componentDidMount

componentWillUnMount

react生命周期函数哪些可以执行多次?

render

shouldComponentUpdate

componentWillUpdate

componentDidUpdate

componentWillReceiveProps

原文地址:https://www.cnblogs.com/950209gkl/p/10113348.html