四个生命周期
涉及到的面试题
1、组件加载的时候第一次执行的生命周期有哪些?
constructor
componentWillMount
cender
componentDidMount
2、那些生命周期会执行一次
constructor
componentWillMount
componentWillunmount
componentDidMount
3、那些生命周期会多次执行
render
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
4、当this.setState执行完毕以后会执行那些生命周期
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate
5、当this.props发生改变的时候会发生那些生命周期
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate
6、当组件的key值发生改变的时候会执行那些生命周期
1、componentWillUnmount
2、constructor
3、componentWillMount
4、render
5、componentDidMount
1、constructor (一次):当前生命周期用来做组件的初始化,当输写了当前生命周期时必须要写super函数,否则this的指向会发生错误
当前生命周期可以用this,state来定义当前组件所需要的一些状态
当前生命周期特殊情况下接收不到props的数据,如果想要接收到props的数据的化,需要在super和constructor中传递props这个
2、componentWillMount:挂载前(一次)
当前生命周期可以接受到props传递过来的数据,可以将外部数据转换成内部数据
在当前生命周期中尽量不要使用this.setState。因为当前生命周期执行完毕后,下个生命周期就是render函数
在当前生命周期中我们可以对this.state中的数据做初始化的做后一次修改
3、render渲染 (多次)
当前生命周期的作用是将数据与虚拟DOM进行相结合,进行数据的渲染,render在第一次执行完毕以后会将渲染的结果在内存中保留一份
当render函数第二次执行的时候,会与内存中的虚拟DOM进行对比,这种对比方式叫做diff算法(diff算法:新旧两个虚拟DOM的对比就是diff算法)
key值的作用
(第一是唯一性第二是稳定性)
做遍历的时候用 为了做标识
4、componentDidMount:挂载后
当前生命周期可以获取到真实的DOM结构,一般情况下我们可以在当前是生命周期中进行ajax的数据请求|| 进行方法的实例
如何获取到真实的DOM结构?
1、this.refs.属性
2、<元素 ref ={(形参)=>this属性=形参}></元素>
(react中形参就代表dom元素)
使用 :this.属性
5、cpmponentWillmount :组件卸载
6、shouldComponentUpdate
当state||props中的数据发生改变的时候会执行当前生命周期,如果返回false则下面的生命周期不会执行(render函数不会执行)
当前生命周期中会有2(3)个参数一个是新的props 一个是新的state 我们可以通过新的props ||state 与旧的props和state作对比,来进行性能优化
3、
4、
componentWillupdate:(多次)(废除)
当前生命周期可以用来做更新数据的最后一次修改
当前生命周期中有2个参数一个是新的props 一个是新的state 我们可以通过新的props||新的state来做数据的最后的一次更改
7、shouldComponentWillUpdate
8、
componentWillReceiveProps:(多次 废除掉了)
当props的数据发生改变的时候当前生命周期就会执行,当前是生命周期中有一个参数就是新的props
在当前