React系列:React的生命週期

React聲明週期

React組件的生命週期可以分爲掛載,渲染,卸載幾個階段。

  1. 組件掛載時:
class App extends Component {
	static propTypes = {
		// ...
	};
	static defaultProps = {
		// ...
	};
	constructor(props) {
		super(props);
		this.state = {
			// ...
		};
	}
	componentWillMount() {
		// ...
	}
	componentDidMount() {
		// ...
	}
	render() {
		return <div>This is a demo.</div>;
	}
}

propTypes和defaultProps分別代表props的類型檢查和默認類型。這兩個屬性被聲明成靜態屬性,意味着從類外面也可以訪問他們。 例如App.propTypes, App.defaultProps

  • 聲明週期componentWillMount會在render之前執行,componentDidMountrender之後執行。
  • componentWillMount componentDidMount都只在組件初始化時運行一次。
  1. 組件卸載時
  • 組件卸載時只有componentWillUnMount這一個狀態,在這裏執行一些清理方法,例如事件回收或者清除定時器
  1. 數據更新過程
class App extends Component {
	//組件由父組件更新props而更新的話,會執行這個方法,可以作爲React在pros傳入後,渲染之前setState的機會,此時調用setState不會二次渲染
	componentWillReceiveProps(nextProps) {
		// this.setState({})
	}
	shouldComponentUpdate(nextProps, nextState) {
	//接收需要更新的props和state,如果返回false,組件將不再向下執行聲明週期方法
		// return true;
	}
	componentWillUpdate(nextProps, nextState) {
		// ... 提供需要更新的props和state
	}
	componentDidUpdate(prevProps, prevState) {
		// ... 提供更新前的props和state
	}
	render() {
		return <div>This is a demo.</div>;
	}
}

注意: 不要在componentWillUpdate中執行setState,
在這裏插入圖片描述

React聲明週期在不同狀態下的執行順序如下:

首次掛載組件:
按順序執行 getDefaultProps, getInitialState, componentWillMount, render, componentDidMount

卸載組件時:
執行componentWillUnMount

重新掛載組件時:

按順序執行 getInitialState, componentWillMount, render, componentDidMount

再次渲染組件時,組件接受到更新狀態
按順序執行componentWillReceiveProps, shouldComponentUpdate, componentWillUpdate, render, componentDidUpdate

注意: 使用ES6 classes來創建React組件時,static defaultProps = {} 就是調用內部的getDefaultProps方法,constructor中的this.state= {} 就是調用getInitialState方法。

圖解React聲明週期執行順序

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章