1. 程式人生 > >React 生命週期(摘抄)

React 生命週期(摘抄)

/*
    首先當元件第一次渲染的時候會執行哪些生命週期函式?
        constructor--->componentWillMount--->render--->componentDidMount

    constructor:
        初始化
        當前生命週期函式可以用來定義當前元件所需要的一些狀態
        當前生命週期裡面必須要寫super如果不寫會報錯/或者this的指向可能發生改變

        如果在super和constructor中沒有傳遞props這個引數的話是訪問不到this.props屬性的,反之可以進行訪問

    componentWillMount:
        元件掛載前:
            在當前生命週期函式裡面可以訪問到props屬性,在這裡可以接受到外部屬性,同時可以將外部屬性轉換為內部屬性

            在當前生命週期函式裡面不需要呼叫setState,因為當前函式執行完畢以後就會執行render函式
    
    render:
        1、render函式什麼時候會執行?
            a、當this.props/this.state發生改變的時候render函式就會去執行。
           
        2、this.props/this.state發生改變的時候會執行哪些生命週期函式

            this.state:
               shouldComponentUpdate--->componentWillUpdate--->render--->componentDidUpdate
            this.props
               componentWillReceiveProps--->shouldComponentUpdate--->componentWillUpdate--->render--->componentDidUpdate

        2、render函式執行的時候會將虛擬DOM和資料進行相結合,在快取中快取一份虛擬DOM,當資料發生改變的時候
        會將虛擬DOM與快取中的虛擬DOM進行比較(diff演算法)。比較完畢以後,將需要修改的虛擬DOM進行批量修改。
        而不是全部修改,減少不必要的更新

        
        3、什麼叫做diff演算法
            新舊兩個虛擬DOM的對比就是tree diff

    componentDidMount:
        render函式執行完畢以後componentDidMount就會去執行。在這個生命週期函式裡面我們可以進行fetch的請求
        以及獲取到真實的DOM結構

    componentWillUnmount:
        元件銷燬


    shouldComponentUpdate:
        1、當this.state/this.props發生改變的時候會執行render函式,
        
        2、shouldComponentUpdate這個生命週期函式必須要返回一個布林值 如果返回true則下面的生命週期函式繼續執行,
        如果返回false下面的生命週期函式不在執行

        3、shouldComponentUpdate這個生命週期函式主要是用來判斷DOM是否更新 而不是資料是否更新(不管返回值是true或者
            false,this.state中的資料肯定會發生改變,但是如果返回值是false的情況下DOM是不會進行更新的
            )

        4、shouldComponentUpdate這個生命週期函式裡面我們可以做一些相關的操作來減少虛擬DOM不必要的更新(利用
            shouldComponentUpdate中接受到的2個引數 一個是新的props 一個是新的state 進行比較
            )

    componentWillUpdate:
          更新前:
            虛擬DOM與資料進行相結合,但是沒有生成真正的DOM結構  

    componentDidUpdate:
            更新後:
                資料和模板進行相結合生產了真正的DOM結構,在這裡可以獲取到資料更新後最新的DOM結構


    componentWillReceiveProps:
            當外部屬性發生改變的時候就會執行當前生命週期函式,當前生命週期函式會有一個引數是新的Prop


        操作DOM的兩種方式
            1、ref="list"  this.refs.list

            2、ref={(tagName)=>{this.key = tagName}}  this.key



        document.getElementById("list")  ||  this.refs  區別?(作業)


    react生命週期函式中有哪些生命週期函式只會執行一次?
        constructor
        componentWillMount
        componentDidMount
        componentWillUnMount

    react生命週期函式中有哪些生命週期函式會執行多次?
        componentWillRecevieProps
        shouldComponentUpdate
        componentWillUpdate
        render
        componentDidUpdate

        

*/