### 裝載過程
組件在裝載過程時,也就是當組件第一次被渲染的時候,會觸發5個鉤子函數:
1. getDefaultProps()
設置默認的props,也可以用dufaultProps設置組件的默認屬性。
2. getInitialState()
在使用es6的class語法時是沒有這個鉤子函數的,可以直接在constructor中定義this.state。此時可以訪問this.props。
3. componentWillMount()
組件初始化時只調用,以后組件更新不調用,整個生命周期只調用一次,此時可以修改state。
4. render()
react最重要的步驟,創建虛擬dom,進行diff算法,更新dom樹都在此進行。此時就不能更改state了。
5. componentDidMount()
組件渲染之后調用,可以通過this.getDOMNode()獲取和操作dom節點,只調用一次。
#### 1. constructor
并不是每個組件都需要定義自己的構造函數,無狀態的React組件往往就不需要定義構造函數。一個React組件需要構造函數,往往是為了下面的目的是初始化state。
通常寫為:
```js
constructor(props) {
super(props)
this.state = {
name: props.name,
age: 18
}
}
```
#### 2. getInitialState 和 getDefaultProps
getInitialState 和 getDefaultProps只在使用 `React.createClass` 定義的組件中有用, 在 ES6 的語法定義中 getInitialState 和 getDefaultProps 兩個方法根本不會用到。
要初始化 state 只需放到 constructor 中,要初始化 props 只需要使用類方法 defaultProps,比如:
```
class Sample extends React.Component {
constructor(props) {
super( props);
this.state = {
foo: 'bar'
};
}
});
Sample.defaultProps = {
return {
sampleProp: 0
}
};
```
#### 3. render
render函數無疑是React組件中最重要的函數,一個React組件可以忽略其他所有函數都不實現,但是一定要實現render函數,因為所有React組件的父類React.Component類對除render之外的生命周期函數都有默認實現。
當然,某些特殊組件的作用不是渲染界面,或者,組件在某些情況下選擇沒有東西可畫,那就讓render函數返回一個null或者false,等于告訴React,這個組件這次不需要渲染任何DOM元素。
需要注意,render函數應該是一個純函數,完全根據this.state和this.props來決定返回的結果,而且不要產生任何副作用。在render函數中去調用this.setState毫無疑問是錯誤的,因為一個純函數不應該引起狀態的改變。
#### 4. componentWillMount 和 componentDidMount
在裝載過程中,componentWillMount會在調用render函數之前被調用,component-DidMount會在調用render函數之后被調用。
需要注意的是,render函數被調用完之后,componentDidMount函數并不是會被立刻調用,componentDidMount被調用的時候,render函數返回的東西已經引發了渲染,組件已經被“裝載”到了DOM樹上。
- 簡介
- 第一章 React入門
- 1.1 創建一個React項目
- 1.2 組件
- 1.3 JSX
- 1.4 eject
- 1.5 渲染
- 第二章 React組件
- 2.1 組件定義
- 2.2 數據處理
- 2.2.1 props
- 2.2.2 state
- 2.3 生命周期
- 2.3.1 裝載過程
- 2.3.2 更新過程
- 2.3.3 卸載過程
- 2.4 事件處理
- 2.5 條件渲染
- 2.6 列表渲染
- 第三章 React高級
- 3.1 靜態類型檢查
- 3.1.1 flow
- 3.1.2 typescript
- 3.2 React Developer Tools
- 第四章 Redux狀態管理
- 4.1 安裝與配置
- 4.2 一個簡單的計數器開始
- 4.3 Store
- 4.3.1 獲取state
- 4.3.2 subscribe
- 4.4 Action
- 4.4.1 Action Creators
- 4.5 Reducer
- 4.5.1 Reducer 的拆分
- 4.6 與其他狀態管理工具的對比
- 第五章 React-Router路由
- 參考資料