2017-03-07 30 views
0

離開組件時不會執行方法當我輸入兩個不同的組件時,需要檢查Facebook的到期日期和當前日期。 DashboardPages。兩者都有這樣的:使用componentWillUnmount()

componentWillMount() { 
    const { linkedAccount, clearLinkedAccounts, getFacebookPages } = this.props 
    const now = moment().format('YYYY-MM-DD HH:mm:ss') 

    if (linkedAccount) { 
    if (now < linkedAccount.expiresIn) { 
     getFacebookPages() 
    } else { 
     clearLinkedAccounts() 
    } 
    } 
} 

componentWillUnmount() { 
    const { linkedAccount, clearLinkedAccounts } = this.props 
    const now = moment().format('YYYY-MM-DD HH:mm:ss') 

    if (linkedAccount && now > linkedAccount.expiresIn) { 
    clearLinkedAccounts() 
    } 
} 

但只有手動刷新頁面時,該clearLinkedAccounts()執行,通過運行componentWillMount,但在離開之前,它沒有。如果有必要,我希望在進入另一條路線之前執行它。

+0

你能否提供反應路由器代碼? –

回答

0

刷新頁面並不像從同一單個應用上下文中的頁面轉到另一頁面。 React router允許您在React單個應用中使用類似Link的標記從一個頁面跳轉到另一個頁面。這就是爲什麼反應路由器如此有用!

當您點擊鏈接轉到另一個頁面Link時,React單個應用仍處於活動狀態。因此,將調用componentWillUnmount,因爲單個應用程序能夠卸載組件。

刷新頁面(F5)時,將加載新頁面。結果,整個現有的單個應用程序被刪除並提供給瀏覽器垃圾收集器。在這種情況下,您無法控制React組件。所以不可能撥打componentWillUnmount,因爲根本沒有更多的組件。