constructor:
当前生命周期函数是用来初始化的,在调取当前函数时,必须在内部要调用super,否则this会出现问题。在当前生命周期函数可以设置本组件需要用到的数据。
在constructor想接受外部数据props时,需要在super中继承过来
componentWillMount:挂载前 (当前生命周期函数在新版本被遗弃
在当前生命周期函数可以降接受的外部数据转为内部数据如:this.state.属性 = this.props.属性。
在当前尽量少用setState,因为该组件执行完后会执行render函数。
可以用来做数据最后一次更改。
render:渲染
当this.setState/this.props发生改变时,会执行render函数
render函数每次执行时将虚拟dom存在缓存中,当下次render函数执行时,会与缓存下来的虚拟dom进行对比(diff算法)将发生改变的虚拟dom进行更新
componentDidMount:挂载后
在当前生命周期函数时,我们可以用this.refs来获取真是dom结构(我们也可以用回调函数获取真实dom结构)
一般在当前生命周期函数时进行ajax请求。
shouldComponentUpdate:
当前生命周期函数必须有个返回值,只有返回值为true时,才会继续执行下面的周期函数。
在此时我们可以做性能的优化,如果当前数据改变后,没有必要进行render渲染,我们可以返回false,减少不必要的渲染。
该生命周期函数有两个参数,一个是新的props,一个是新的state
当前生命周期函数决定render函数是否渲染(页面是否更新),不会影响数据是否更新(如:当通过点击事件执行一个异步更改数据,虽然返回false,数据仍然可以更新)
componentWillUpdate
当前函数用于作数据最后的更新处理,该生命周期函数有两个参数,一个是新的props,一个是新的state
componentDidUpdate
当前生命周期是数据更新完,获取最新的dom,该生命周期函数有两个参数,一个是旧的props,一个是旧的state
componentWillReceiveProps
当this.props值发生改变时候,会执行该生命周期,有一个参数,该参数为修改后的值,作用:用于修改外部传过来的数据
总结:
1,第一次执行的生命周期函数
constructor componentWillMount render componentDidMount
2,只会执行一次的生命周期函数
constructor componentWillMount componentDidMount componentWillUnmount
3,当this.props/this.state发生改变时会执行的生命周期函数:
this.state: shouldComponentUpdate componentWillUpdate componentDidUpdate render
this.props:componentWillReceiveProps shouldComponentUpdate componentWillUpdate componentDidUpdate rende
4,会执行多次的生命周期函数:
render componentWillReceiveProps shouldComponentUpdate componentWillUpdate componentDidUpdate rende