React16 生命週期理解

完整生命週期

constructor(props) // 初始化參數

componentWillMount()

render() // 第一次渲染 

componentDidMount()

當父組件向子組件傳入props發生改變後,依次調用

componentWillReceiveProps(nextProps)

shouldComponentUpdate(nextProps, nextState) 

componentWillUpdate()

render() //子組件更新渲染

componentDidUpdate()

當組件自身state發生變化後

componentWillUpdate()

render() //組件再次更新渲染

componentDidUpdate()

當組件卸載

componentWillUnmount()

生命週期詳解

componentDidMount() 此處請求接口數據 
componentWillReceiveProps(nextProps) 子組件獲得新props時觸發,作用是在子組件再次渲染前,更新子組件自身的state,之後會觸發shouldComponentUpdate()   
shouldComponentUpdate(nextProps, nextState) 接受的props發生變化或者自身state變化都會觸發該生命週期,在此生命週期可以做一些渲染的優化,默認返回true,就是默認需要更新組件,重新渲染,nextProps nextState 都是新state 新props,this.props this.state 表示舊的props state,根據需求做優化,比如在某些情況下返回false,便不再進行組件更新了,提升頁面性能

例子

這個例子讓你更好的理解幾個生命週期的作用 Github地址在這裏

圖片描述

圖片描述

參考react官方文檔 State & 生命週期 && 性能優化 章節
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章