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"));