1. 程式人生 > 其它 >React Native 生命週期

React Native 生命週期

在iOS的世界裡,檢視是有生命週期的,比如檢視載入,檢視將要出現,或者檢視銷燬等階段,

同理在React Native的生命週期裡也是有類似階段的,網上有很多例子,過程叫法也不太一樣,

個人感覺總體是三個階段:

掛載階段、執行階段、解除安裝階段

一、掛載階段

檢視從建立--->初始化---->載入完成階段,

類似iOS原生alloc initviewDidLoad(建立、初始化、檢視載入完成)

也有稱這個階段為建立階段和例項化階段,個人感覺就是建立一個檢視物件的過程,從無到有,能看到介面的過程

componentWillMount和原生的viewWillAppear是不一樣的,componentWillMount只會呼叫一次

本階段對我們來講比較重要的就是:

constructor方法中寫super(props);使我們能夠用this訪問屬性,對state進行初始化this.state

componentDidMount方法中寫網路請求,在網路請求資料回撥中通過setState方法改變狀態

constructor(props: IProp) {
        super(props);
        this.state = {}
    }

    componentDidMount() {
        ServicesApiDistinguish.echelon().then((res) => {
            
if (null != res) { if (200 == res.code) { this.setState({ }); } else { Toast.info(res.message, 1) } } }); }
getDefaultProps?(): P;
getInitialState
?(): S;

二、執行階段

就是檢視存在期間的階段,更新頁面等等之類的,換言之就是掛掉之前的階段

也有稱這個階段為更新階段的

我們可以通過setState來更新我們的介面,或者來自父元件的props的改變,componentWillReceiveProps

componentWillMount、componentDidMount和componentWillUpdate、componentDidUpdate可以對應起來。 區別在於,前者只有在掛載的時候會被呼叫;而後者在以後的每次更新渲染之後都會被呼叫。
ps:絕對不要在componentWillUpdate和componentDidUpdate中呼叫this.setState方法,否則將導致無限迴圈呼叫

三、解除安裝階段

就是檢視移除的階段

也有稱這個階段為銷燬階段的

此階段比較重要的方法componentWillUnmount(),類似dealloc方法

當元件要被從介面上移除的時候,就會呼叫 componentWillUnmount。
在這個函式中,可以做一些元件相關的清理工作,例如取消計時器、網路請求等。

參考資料:https://www.jianshu.com/p/72f8c1da0b65