問題
理解React組件的生命周期
知識點
React流程狀態(tài)圖

React流程狀態(tài)圖.png
注意:流程狀態(tài)圖為使用React.createClass方法的生命周期
- 使用
ajax獲取后臺數(shù)據(jù)渲染時,一般將調(diào)用ajax方法放在componentDidMount中,這樣可以先渲染虛擬dom再展示數(shù)據(jù),當再次調(diào)用ajax數(shù)據(jù)改變時,dom內(nèi)數(shù)據(jù)會再次渲染,而不用再次加載整個dom。如果在該dom要根據(jù)條件只通過ajax獲取一次數(shù)據(jù),則可以將調(diào)用ajax的方法放在componentWillMount。 - 當工程中未加載
jQuery,異步請求也可以使用fetch等 - 在
componentWillUpdate中,盡量避免使用setState()或setProps()方法。若無條件判斷情況下使用setState()或setProps(),會導致死循環(huán),同樣componentDidUpdate中使用setState()若無條件限制也會導致死循環(huán)。 - 通過
shouldComponentUpdate可以對是否進行渲染的條件判斷,能夠作為性能調(diào)優(yōu)的手段,避免無意義渲染。 -
componentWillReceiveProps可以通過nextProps獲取新傳入的參數(shù)值,例如:nextProps.operationType獲取operationType - 建議使用
setState()的周期為:componentWillMount、componentDidMount、componentWillReceiveProps、componentDidUpdate - 注意對應周期中
this.state的值
通過列表樹構(gòu)建后總結(jié)補充:
-
setState不會立即生效,要經(jīng)過render過程才能真正改變state值 - 在
return時調(diào)用方法setState,會引起shouldComponentUpdate周期,而此時componentDidMount周期已完成。
參考文章
React組件生命周期過程說明
React組件生命周期
React數(shù)據(jù)獲取為什么一定要在componentDidMount里面調(diào)用?