React生命周期渲染示意
子組件不添加props,父shouldComponentUpdate返回true時:
子組件不添加props,父shouldComponentUpdate返回false時:
子組件添加props,並且改變props值,父shouldComponentUpdate返回false時:
子組件添加props,並在父改變傳值,並且子組件添加一個動態的key,父組件還是shouldComponentUpdate返回false:
綜上實驗,暫時可以得出一個結論,shouldComponentUpdate是子組件重新渲染的閥門,可控制子組件更新和掛載。
繼續,再考慮一種情況
給子組件添加一個動態的key,不傳props,子組件不使用props,shouldComponentUpdate返回true:
給子組件添加一個動態的key,並給子組件傳props,shouldComponentUpdate返回true:
綜上所述,暫時還可以得出一個結論,子組件上動態的key,不管是否有傳值變化都會觸發組件的重新掛載。
繼續進行試驗,不考慮shouldComponentUpdate和動態key。
子組件上加props,並在子組件使用,值發生變化和不發生變化:
子組件不添加props,不添加動態key,不調用shouldComponentUpdate函數:
綜上實驗:
組件更新數據有兩個情況:
1,更新父組件,子組件就會執行receiveProp和render不管是否有數據變化,不會重新掛載。
2,組件重新掛載,組件重新會執行一遍掛載的生命周期,掛載點組件發生變化。
組件是否更新,受到shouldComponentUpdate的判斷控制:
1,組件是否有值變化
2,組件是否需要重新掛載
shouldComponentUpdate返回false時,都不會執行更新!!!
組件被當做子組件使用時,就會觸發 componentWillReceiveProps () 周期函數。
另外,還有需要一組需要留意的生命周期函數 update
update是在render之前,mount是在之后,有dom結構才需要掛載。
Redux 對React生命周期變化的影響
在state發生變化時,會觸發以下生命周期執行:
--- componentWillReceiveProps ---
--- componentWillReceiveProps ---
--- componentWillUpdate ---
--- componentDidUpdate ---
在組件內調用 shouldComponentUpdate,這個生命周期鈎子還是會影響組件的渲染。