React生命周期调用函数介绍
var MainComponent = React.createClass({
//设置数据的默认值
getDefaultProps: function () {
console.log("getDefaultProps");
return {name: 'null'};
}
//在组件加载之前调用一次,返回值作为this.state的初始值
, getInitialState: function () {
console.log("getInitialState");
return {count: 0};
},
//在完成首次渲染之前调用
componentWillMount: function () {
console.log("componentWillMount");
},
//必选的方法,创建虚拟DOM
//只能通过this.state和this.props访问数据
//可以返回null,false或任何React组件
//只能出现一个顶级组件(不能返回数组)
//不能改变组件的状态
//不能修改DOM的输出
//一、
render:function () {
console.log("render");
return <div>MainComponent</div>
},
//二、
render: ()=> {
console.log("render");
return <div>MainComponent</div>
},
// 真实的DOM被渲染出来后调用,在该方法中可通过this.getDOMNode()访问到真实的DOM元素
componentDidMount: function () {
console.log("componentDidMount");
}
,
// 组件接收到新的props时调用,并将其作为参数nextProps使用
componentWillReceiveProps: function (nextProps) {
console.log("componentWillReceiveProps");
if (nextProps.bool) {
this.setState({
bool: true
})
;
}
},
//组件是否需要渲染新的props或state,返回false表示跳过后续的生命周期方法,通常不需要使用,以免出现bug
shouldComponentUpdate: function () {
return true;
},
//接受到新的props或者state后,进行渲染之前调用
componentWillUpdate: function () {
console.log("componentWillUpdate");
},
// 完成渲染新的props或者state调用,此时可以访问到新的DOM元素
componentDidUpdate: function () {
console.log("componentDidUpdate");
}
//组件被移除之前调用,可以做一些清理工作,在conponentDidMount方法中添加的所有任务都需要在该方法中撤销
, componentWillUnmount: function () {
console.log("componentWillUnmount");
}
});
ReactDOM.render(<MainComponent/>, document.getElementById("content"));