react 組件的生命週期

 

 

 

組件生命週期函數總覽

  • 組件的生命週期包含三個階段:建立階段(Mounting)、運行和交互階段(Updating)、卸載階段(Unmounting)
  • Mounting:
constructor() 
componentWillMount() 
render() 
componentDidMount()
  • Updating
componentWillReceiveProps() 
shouldComponentUpdate() 
componentWillUpdate() 
render() 
componentDidUpdate()
  • Unmounting
componentWillUnmount()

組件生命週期 - 建立階段(Mounting)

  • 特色:該階段的函數只執行一次

constructor()

  • 做用:1 獲取props 2 初始化state
  • 說明:經過 constructor() 的參數props獲取
  • 設置state和props

 

componentWillMount()

  • 說明:組件被掛載到頁面以前調用,其在render()以前被調用,所以在這方法裏同步地設置狀態將不會觸發重渲染
  • 注意:沒法獲取頁面中的DOM對象
  • 注意:能夠調用 setState() 方法來改變狀態值
  • 用途:發送ajax請求獲取數據

render()

  • 做用:渲染組件到頁面中,沒法獲取頁面中的DOM對象
  • 注意:不要在render方法中調用 setState() 方法,不然會遞歸渲染javascript

    • 緣由說明:狀態改變會從新調用render()render()又從新改變狀態

 

componentDidMount()

  • 1 組件已經掛載到頁面中
  • 2 能夠進行DOM操做,好比:獲取到組件內部的DOM對象
  • 3 能夠發送請求獲取數據
  • 4 能夠經過 setState() 修改狀態的值
  • 注意:在這裏修改狀態會從新渲染
componentDidMount() {
  // 此時,就能夠獲取到組件內部的DOM對象 console.warn('componentDidMount', document.getElementById('btn')) }

 

組件生命週期 - 運行階段(Updating)

  • 特色:該階段的函數執行屢次
  • 說明:每當組件的props或者state改變的時候,都會觸發運行階段的函數

 

componentWillReceiveProps()

  • 說明:組件接受到新的props前觸發這個方法
  • 參數:當前組件props
  • 能夠經過 this.props 獲取到上一次的值
  • 使用:若你須要響應屬性的改變,能夠經過對比this.propsnextProps並在該方法中使用this.setState()處理狀態改變
  • 注意:修改state不會觸發該方法
 


componentWillReceiveProps(nextProps) { console.warn('componentWillReceiveProps', nextProps) }

shouldComponentUpdate()

  • 做用:根據這個方法的返回值決定是否從新渲染組件,返回true從新渲染,不然不渲染
  • 優點:經過某個條件渲染組件,下降組件渲染頻率,提高組件性能
  • 說明:若是返回值爲false,那麼,後續render()方法不會被調用
  • 注意:這個方法必須返回布爾值!!!
  • 場景:根據隨機數決定是否渲染組件
 
// - 參數: // - 第一個參數:最新屬性對象 // - 第二個參數:最新狀態對象 shouldComponentUpdate(nextProps, nextState) { console.warn('shouldComponentUpdate', nextProps, nextState) return nextState.count % 2 === 0 }

componentWillUpdate()

  • 做用:組件將要更新
  • 參數:最新的屬性和狀態對象
  • 注意:不能修改狀態 不然會循環渲染

render() 渲染

  • 做用:從新渲染組件,與Mounting階段的render是同一個函數
  • 注意:這個函數可以執行屢次,只要組件的屬性或狀態改變了,這個方法就會從新執行

componentDidUpdate()

  • 做用:組件已經被更新
  • 參數:舊的屬性和狀態對象

組件生命週期 - 卸載階段(Unmounting)

  • 組件銷燬階段:組件卸載期間,函數比較單一,只有一個函數,這個函數也有一個顯著的特色:組件一生只能執行依次!
  • 使用說明:只要組件再也不被渲染到頁面中,那麼這個方法就會被調用( 渲染到頁面中 -> 再也不渲染到頁面中 )

componentWillUnmount()

  • 做用:在卸載組件的時候,執行清理工做,好比html

    • 1 清除定時器
    • 2 清除componentDidMount建立的DOM對象

 

相關文章
相關標籤/搜索