一、React的生命周期有几个阶段
React的生命周期分为三个阶段:
1. Mounting:React的Components被render进行解析,生成对应的DOM节点,并被插入浏览器DOM结构的过程。
2. Updating:一个React的Components的State值发生改变并影响了DOM结构,就重新render解析它。
3. Unmounting:React的销毁
生命周期图:
二、React的Mounting阶段
Mounting中的getIntialState()函数会初始化component的state值。
componentWillMount函数,他会在component被解析之前被调用。
通过render解析React语句,生成DOM节点。
解析完之后,调用componentDidMount函数。
我使用的是JSRUN在线编辑器,用它来测试是否正确。
var Hello = React.createClass({
getInitialState: function(){
alert('init');
return {
opacity: 1.0,
fontSize: '4px'
};
},
render : function() {
return <div>Hello {this.props.title} {this.props.name}</div>;
},
componentWillMount: function(){
alert('Will');
},
componentDidMount: function(){
alert('Did');
}
});
React.render(<Hello name = "World" title = "Mrs"/>,
document.getElementById('container'));
init首先被alert方法显示了出来,接着是Will,Will之后 Hello Mrs World被解析渲染了出来,最后是Did,说明在Mounting阶段,以上函数按顺序调用。
二、React的Updating阶段
下面那三个跟第一阶段的Mounting里面的是一样的,因为要判断是否有必要重新解析渲染DOM节点,有必要则Mounting。
重点是上面两个函数,componentWillReceiveProps和shouldComponentUpdate
componentWillReceiveProps,当一个Mounting的component接收一个新的props的时候,这个函数就会被调用,其函数的参数就是新的props对象,对其进行修改更新。
shouldComponentUpdate,当一个新的props被接收并修改之后,判断有无必要更新DOM结构,返回true则进行再进行解析三步骤,flase则跳过解析变更。该函数的参数有两个,一个是新的props对象与新的state对象。
三、React的Unmounting阶段
该阶段只有一个hook函数可以调用,即componentWillUnmount。
可以调用它里面的clean up清空资源,释放内存。但由于浏览器的垃圾回收机制,我们可以不太需要去考虑销毁的问题。