React严格定义了组件的生命周期,生命周期会经历如下三个过程:
1.装载过程(Mount),也就是把组件第一次在DOM树中渲染过程;
2.更新过程(Update),当组件被重新渲染的过程;
3.卸载过程(Unmount),组件从DOM中删除的过程;
三个过程,React库会依次调用组件的一些成员函数(生命周期函数)
装载过程(第一次被渲染的时候,一次会调用如下函数)
constructor
getInitialState
getDefaultProps
componentWillMount
render
componentDidMount
1.constructor:
1.初始化State
2.绑定成员函数的this环境
//在ES6语法下:类的每个成员函数在执行时的this并不会和类实例自动绑定。而在构造函数中,this就是当前组件的实例,所以,为了将来方便调用,会在构造函数中将特定函数绑定this为当前实例。
//注意在原生的js中,类的每个成员函数是会和类实例自动绑定的。
this.onClickDecrementButton = this.onClickDecrementButton.bind(this);
this.onClickIncrementButton = this.onClickIncrementButton.bind(this);
getInitialState和getDefaultProps方法在ES6方法定义的React组件中使用不到。
render函数:
render函数是React组件中最重要的函数,一个React组件可以忽略其他函数不实现,但是一定要实现render函数,因为所有React组件的父类React.Component类对除render之外的生命周期函数都有默认实现。
//componentWillMount会在调用render函数之前被调用。(将要装载)
//通常不定义componentWillMount函数,这个时候即使调用this.setState修改状态也不会发生重新绘制。
componentWillMount() {
console.log('enter componentWillMount ' + this.props.caption);
}
//componentDidMount会在调用render函数之后调用。(装载完毕),此时render返回的东西已经发生了渲染
//组件的componentDidMount方法是在render后一起用的
componentDidMount() {
console.log('enter componentDidMount ' + this.props.caption);
}
更新过程:
更新过程会调用以下函数:
1.componentWillReceiveProps
(componentWillReceiveProps:实际上,只要父组件的render函数被调用,在render函数中被渲染的子组件就会经历更新过程,不管父组件传给子组件的props有没有改变,都会触发子组件的componentWillReceiveProps函数。)
(注意:通过this.setState方法触发的更新过程不会调用这个函数,这是因为这个函数适合根据新的props值(也就是参数 nextProps)来计算出是不是要更新内部状态)。(更新组件内部状态的方法就是this.setState,如果this.setState的调用导致componentWillReceiveProps 再一次被调用,那就是一个死循环了)。
所以,这个函数有必要把传入参数nextProps和this.props值变化的时候才有必要调用this.setState 更新内部的状态。
2.shouldComponentUpdate
3.componentWillUpdate
4.render
5.componentDidUpdate
shouldComponentUpdate(nextProps,nextState)
除了render函数,shouldComponentUpdate可能是React组件生命中最重要的一个函数。
说render 函数重要,是因为render函数决定了该渲染什么,而说shouldComponentUpdate 函数重要,是因为它决定了一个组件什么时候不需要渲染。
render 和 shouldComponentUpdate 函数是React生命周期函数中唯2 两个要求有返回值的函数。render函数的返回结果用于构造DOM对象,而shouldComponentUpdate函数 返回一个布尔值,告诉react组件在这次更新中是否要继续。
//shouldComponentUpdate 参数接下来的props和state值
shouldComponentUpdate(nextProps, nextState) {
return (nextProps.caption !== this.props.caption) || (nextState.count !== this.state.count);
}
1.componentWillUpdate 与 componentDidUpdate
如果组件的shouldComponentUpdate 返回结果是true,React接下来就会依次调用对应组件的componentWillUpdate 、render、componentDidUpdate函数。
componentWillMount 和 componentDidMount, componentWillUpdate 和 componentDidUpdate,这两个函数一前一后把render函数夹在中间。
和装载过程不同是,当在服务端使用React渲染时,这一对函数中的Did函数,也就是componentDidUpdate函数,并不只在浏览器端才执行的,无论更新过程发生在服务器端还是浏览器端,该函数都会被调用。
在介绍componentDidMount函数时,我们可以说到可以利用componentDidMount函数执行其他UI库的代码,比如JQuery代码。当React组件被更新时,原有的内容被重新绘制,这时候就需要在componentDidUpdate 函数中再次调用jQuery代码。
卸下过程
React组件的卸载过程只涉及一个函数componentWillUnmount,当React组件要从DOM树上删除之前,对应的componentWillUnmount调用,所以这个函数适合做一些清理工作。
参考《深入浅出React和Redux》