component是通過自定義的幾個函數來控制組件在生命周期中的各個階段動作(本處所寫的state同意指當前組件內部定義的state)
- constructor(props, context)
構造函數,在創建組件的時候調用一次,props為父組件傳到子組件中的所有屬性集合
- componentWillMount()
在組件加載前執行一次,如果在該處更新state,組件渲染時是讀取到的是最新的state。
- componentDidMount()
在組件加載后執行一次,此時組件已渲染過一次,可調用this.refs獲取DOM節點
- componentWillReceiveProps(nextProps)
nextProps是父組件傳遞給子組件的最新props。子組件已加載,父組件發生render的時候子組件就會
調用componentWillReceiveProps(不管props有沒有更新,也不管父子組件之間有沒有數據交換)
- shouldComponentUpdate(nextProps, nextState)
返回boolean值,默認返回true。nextProps是父組件傳遞給子組件的最新props,nextState為子組件最新的state。
通過返回true/false來控制子組件是否需要重新渲染。有一些數據的改變并不需要重新渲染,在該處就可以攔截,做優化處理。
- componentWillUpdate(nextProps, nextState)
shouldComponentUpdate返回true或者調用forceUpdate之后,componentWillUpdate會被調用
- componentDidUpdate(preProps, preState)
除了首次render之后調用componentDidMount,其它render結束之后都是調用componentDidUpdate。
componentWillMount、componentDidMount和componentWillUpdate、componentDidUpdate可以對應起來。區別在于,前者只有在掛載的時候會被調用;而后者在以后的每次更新渲染之后都會被調用。
- componentWillUnmount()
組件被卸載的時候調用。一般在componentDidMount里面注冊的事件需要在這里刪除。
觸發render方法
在react中,觸發render的有4條路徑。
以下假設shouldComponentUpdate都是按照默認返回true的方式。
首次渲染Initial Render
調用this.setState (并不是一次setState會觸發一次render,React可能會合并操作,再一次性進行render)
父組件發生更新(一般就是props發生改變,但是就算props沒有改變或者父子組件之間沒有數據交換也會觸發render)
調用this.forceUpdate
常用語法
- class 屬性需要寫成 className ,for 屬性需要寫成 htmlFor ,這是因為 class 和 for 是 JavaScript 的保留字。
- style={{}} 最外層{}告訴jsx這是js語法,而里面的{}表示樣式包裹成對象
- this.props 獲取當前組件的props屬性對象。
- this.state 獲取當前組件的state狀態值對象
- this.setState 更新當前組件state狀態值對象(使用redux后不建議在組件內使用自身的state)
- this.props.children 獲取組件的所有子節點,使用React.Children.map來遍歷,從而忽略掉this.props.children返回值的類型
- this.refs.[refName] 獲取真實DOM節點,故必須在組件render后調用
<input type="text" ref="myTextInput" />
獲取該節點:this.refs.myTextInput;
- PropTypes 用來驗證組件的props入參是否符合要求
Index.propTypes = {
value: PropTypes.string.isRequired,
onIncreaseClick: PropTypes.func.isRequired,
onReduceClick: PropTypes.func.isRequired
}
- key 循環輸出元素時,用來唯一標識同父同層級的兄弟元素,當React作diff時,只要子元素有key屬性,便會去原v-dom樹中相應位置(當前橫向比較的層級)尋找是否有同key元素,比較它們是否完全相同,若是則復用該元素,免去不必要的操作。故不推薦用數組index來作為key,可用數據對象的某個唯一屬性,或是對數據進行hash來生成key。
- 求值表達式 使用{}包起來,在{}中不能直接使用if/for語句,但可以返回值表達式
- 條件判斷 使用三元表達式來期待if-else,善用比較運算符“ || ”
- 函數表達式 使用(function(){})()來強制執行函數,返回值
- 注釋 {/* 一般注釋, 用 {} 包圍 */}
React框架把component看作一個狀態機,通過改變狀態值來控制頁面view的輸出,其實你可以看成React框架注重數據與DOM的分離,用數據變化來控制DOM的變化,不同于jQuery直接對DOM對象的操作。
- 向react中插入HTML字符串
<div className="place_list" dangerouslySetInnerHTML={{__html: mapPlace()}} onClick={this.handleChooseCity.bind(this)}>
</div>
- 在react的組件中實現路由跳轉 this.props.history.push(url)