1. 程式人生 > >React從0到1--元件生命週期

React從0到1--元件生命週期

1、React 嚴格定義了元件的生命週期,生命週期可能會經歷如下三個過程
裝載過程( Mount),也就是把元件第一次在 DOM 樹中渲染的過程;
更新過程( Update ),當元件被重新渲染的過程;
解除安裝過程( Unmount),元件從 DOM 中刪除的過程

2、裝載過程

我們先來看裝載過程,當元件第一次被渲染的時候,依次呼叫的函式是如下這些:
constructor
getlnitialState
getDefaultProps
componentWillMount
render
componentDidMount

1. constructor
  
Es6中建立一個元件的例項,無狀態的React元件不需要例項

1、初始化state

this.state = {
count: props.initValue || 0
}

2、繫結成員的this環境

this.onClickIncButton = this.onClickIncButton.bind(this);
this.onClickDecButton = this.onClickDecButton.bind(this);

3、getlnitialState 和 getDefaultProps
React.createClass 方法創造的元件類才會用到這兩種方法,分別用來初始化state和props