組件的生命週期
- 生命週期的概念:每個組件的實例,從創建、到運行、直到銷燬,在這個過程中,會觸發一系列事件,這些事件就叫做組件的生命週期函數。
- React組件生命週期分爲三部分:
1.組件創建階段:特點:一輩子只執行一次
componentWillMount:在渲染前調用
render
componentDidMount:在第一次渲染後調用,之後組件已經生成了對應的DOM結構,可以通過this.getDOMNode()來進行訪問。如果你想和其他JavaScript框架一起使用,可以在這個方法中調用setTimeout,setInterval或者發送AJAX請求等操作。
2.組件運行階段:按需,根據props屬性或state狀態的改變,有選擇性的執行0到多次
componentWillReceiveProps:在組件接收到一個新的prop時被調用
shouldComponentUpdate:返回一個布爾值,在組件接收到新的props或者state時被調用。
componentWillUpdate:在組件接收到新的props或者state但還沒有render時被調用。
render
componentDidUpdate:在組件完成更新後立即調用。
3.組件銷燬階段:一輩子只執行一次
componentWillUnmount:在組件從DOM中移除之前立刻被調用。
React生命週期函數圖解:
React生命週期函數的使用:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React 實例</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
class Button extends React.Component {
constructor(props) {
super(props);
this.state = {data: 0};
this.setNewNumber = this.setNewNumber.bind(this);
}
setNewNumber() {
this.setState({data: this.state.data + 1})
}
render() {
return (
<div>
<button onClick = {this.setNewNumber}>INCREMENT</button>
<Content myNumber = {this.state.data}></Content>
</div>
);
}
}
class Content extends React.Component {
componentWillMount() {
console.log('Component WILL MOUNT!')
}
componentDidMount() {
console.log('Component DID MOUNT!')
}
componentWillReceiveProps(newProps) {
console.log('Component WILL RECEIVE PROPS!')
}
shouldComponentUpdate(newProps, newState) {
return true;
}
componentWillUpdate(nextProps, nextState) {
console.log('Component WILL UPDATE!');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component DID UPDATE!')
}
componentWillUnmount() {
console.log('Component WILL UNMOUNT!')
}
render() {
return (
<div>
<h3>{this.props.myNumber}</h3>
</div>
);
}
}
ReactDOM.render(
<div>
<Button />
</div>,
document.getElementById('example')
);
</script>
</body>
</html>
當第一次加載以上頁面時控制檯會打印:
Component WILL MOUNT!
Component DID MOUNT!
當點擊按鈕更新Content組件的值時,控制檯會打印:
Component WILL RECEIVE PROPS!
Component WILL UPDATE!
Component DID UPDATE!
當關閉網頁時控制檯會打印:
Component WILL UNMOUNT!(當然這條信息我們是看不到的,因爲頁面已經被關閉了)