React生命周期详解

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

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

constructor:

初始化

当前生命周期函数可以用来定义当前组件所需要的一些状态

当前生命周期里面必须要写super如果不写会报错/或者this的指向可能发生改变

如果在super和constructor中没有传递props这个参数的话是访问不到this.props属性的,反之可以进行访问

componentWillMount:

组件挂载前:

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

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

render:

1、render函数什么时候会执行?

a、当this.props/this.state发生改变的时候render函数就会去执行。

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

this.state:

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

this.props

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

2、render函数执行的时候会将虚拟DOM和数据进行相结合,在缓存中缓存一份虚拟DOM,当数据发生改变的时候

会将虚拟DOM与缓存中的虚拟DOM进行比较(diff算法)。比较完毕以后,将需要修改的虚拟DOM进行批量修改。

而不是全部修改,减少不必要的更新

3、什么叫做diff算法

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

componentDidMount:

render函数执行完毕以后componentDidMount就会去执行。在这个生命周期函数里面我们可以进行fetch的请求

以及获取到真实的DOM结构

componentWillUnmount:

组件销毁

shouldComponentUpdate:

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

2、shouldComponentUpdate这个生命周期函数必须要返回一个布尔值 如果返回true则下面的生命周期函数继续执行,

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

3、shouldComponentUpdate这个生命周期函数主要是用来判断DOM是否更新 而不是数据是否更新(不管返回值是true或者

false,this.state中的数据肯定会发生改变,但是如果返回值是false的情况下DOM是不会进行更新的

)

4、shouldComponentUpdate这个生命周期函数里面我们可以做一些相关的操作来减少虚拟DOM不必要的更新(利用

shouldComponentUpdate中接受到的2个参数 一个是新的props 一个是新的state 进行比较

)

componentWillUpdate:

更新前:

虚拟DOM与数据进行相结合,但是没有生成真正的DOM结构

componentDidUpdate:

更新后:

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

componentWillReceiveProps:

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

操作DOM的两种方式

1、ref="list" this.refs.list

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

document.getElementById("list") || this.refs 区别?(作业)

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

constructor

componentWillMount

componentDidMount

componentWillUnMount

react生命周期函数中有哪些生命周期函数会执行多次?

componentWillRecevieProps

shouldComponentUpdate

componentWillUpdate

render

componentDidUpdate

原文地址:https://www.cnblogs.com/zdhBK/p/10123431.html