React聲明週期
React組件的生命週期可以分爲掛載,渲染,卸載幾個階段。
- 組件掛載時:
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
之前執行,componentDidMount
在render
之後執行。 componentWillMount
componentDidMount
都只在組件初始化時運行一次。
- 組件卸載時
- 組件卸載時只有componentWillUnMount這一個狀態,在這裏執行一些清理方法,例如事件回收或者清除定時器
- 數據更新過程
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
方法。