深入了解React組件重新渲染的條件和生命周期


React組件rerender的真正條件

  1. 當前組件的State中的屬性改變時且當前組件的shouldcomponentupdate返回true,那么當前組件會rerender

  2. 組件的props中的任一屬性的值有變化(即使這個任一屬性的值是對象,變化的僅僅是該對象中的某屬性的值,此刻也算props發生了變化)且當前組件的shouldcomponentupdate return true時且當期組件所有父級以上組件的shouldcomponentupdate return true,當前組件才會re-render

  3. 當前組件的shouldcomponentupdate即使返回false,當前組件里子組件若滿足1中的條件,這個子組件依然會重新渲染

各個生命周期的深層含義

shouldComponentUpdate

觸發時機1:

when new props(當props中某屬性的值為對象時,該對象中某屬性值發生了變化,也會觸發該函數的調用) are being received且所有父級組件的shouldComponentUpdate得返回true當前組件才會觸發該回調

觸發時機2:

即使所有父級組件的shouldComponentUpdate返回false,當前組件的state有變化,當前組件的該回調依然會觸發

默認值

Defaults to true. This method is not called for the initial render or when forceUpdate() is used

其他情況

if shouldComponentUpdate() returns false, then componentWillUpdate(), render(), and componentDidUpdate() will not be invoked

componentWillReceiveProps

觸發時機1:

當當前組件的props某屬性有變化時(包括這種情況:當props中某屬性的值為對象時,該對象中某屬性值發生了變化)且所有父級以上組件的shouldComponentUpdate返回true(當前組件的shouldComponentUpdate是否返回true不重要)時當前組件的該回調才會觸發調用

觸發時機2:

即使當前組件的shouldComponentUpdate return false且當前組件沒有props的更新,父級組件re-render了,當前組件該函數還是會觸發調用

組件第一次渲染完成:mounting

mouting含義

whenever the Clock is rendered to the DOM for the first time. This is called "mounting" in React

在組件內相應回調函數叫componentDidMount() componentWillMount

組件被銷毀時:Unmounting

whenever the DOM produced by the Clock is removed. This is called "unmounting" in React

在組件內相應回調函數叫componentWillUnmount()

組件正在被重新渲染: Updating

在組件內相應回調函數叫componentWillUpdate componentDidUpdate


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM