React组件有以下生存周期
1、getDefaultProps
获取默认的props熟悉,最先执行,主要用于初始化props
2、getInitialState
获取初始的state状态
3、componentWillMount
新创建组件后即将被渲染
4、render
组件渲染
5、componentDidMount
组件完成渲染
6、componentWillUpdate
已经存在的组件状态发生变化即将被更新
7、componentWillUnmount
组件将销毁
8、componentWillReceiveProps
接受到props的设置,render之前,再次期间可以设置setState不引起二次渲染,旧的props可以用this.props获取,新的props为该方法的参数
10、shouldComponentUpdate
接收到新的state或props时,render之前调用,此期间可以验证传入的值确定是否允许试图更新。
以下代码可以跟踪组件的执行过程
var Main = React.createClass({
getDefaultProps:function(){
console&&console.log('component getDefaultProps',Date.now());
},
getInitialState: function () {
console&&console.log('component getInitialState',Date.now());
return {};
},
componentWillMount: function () {
console&&console.log('component will mount',Date.now());
},
componentDidMount: function () {
console&&console.log('component did mount',Date.now());
},
componentWillUpdate: function () {
console&&console.log("componentWillUpdate",Date.now());
},
componentDidUpdate: function () {
console&&console.log('component did update',Date.now());
},
componentWillUnmount: function () {
console&&console.log('component will unmount',Date.now());
},
updateChildHandler:function(){
console.log(this.refs);
},
render: function () {
console&&console.log('component render',Date.now());
return (<div className="main"><h1>hello world</h1><a href="javascript:void(0)" onClick={this.updateChildHandler}>更新孩子</a><RouteHandler ref="childref"/></div>)
}
});