2016-06-17 225 views
2

我正在使用Reactjs.I當他點擊後退按鈕時要警告用戶。 我所母鹿是ReactJs瀏覽器後退按鈕

handleWindowClose = (ev) => { 
    ev.preventDefault(); 
    return ev.returnValue = 'Leaving this page will loose data'; 
} 

componentDidMount =() => { 
    window.addEventListener('beforeunload',this.handleWindowClose);  
} 

componentWillUnmount =() => { 
    window.removeEventListener('beforeunload',this.handleWindowClose); 
} 

但是這並不後退按鈕click.So我試着這樣做

handleWindowClose = (ev) => { 
     ev.preventDefault(); 
     return ev.returnValue = 'Leaving this page will loose data';   
} 

onBackButtonEvent = (e) => { 
    e.preventDefault(); 
    if(confirm("Do you want to loose this data")){ 
    window.history.go(0); 
    }else { 
    window.history.forward(); 
    } 
} 

componentDidMount =() => { 
    window.addEventListener('beforeunload',this.handleWindowClose);  
    window.addEventListener('popstate',this.onBackButtonEvent); 
} 

componentWillUnmount =() => { 
    window.removeEventListener('beforeunload',this.handleWindowClose); 
    window.removeEventListener('popstate',this.onBackButtonEvent); 
} 

我沒有使用react-router.Is有沒有更好的方式做工作這隻使用react.Also我希望窗口留在該頁面上,而不使用history.forward(),因爲我將失去窗口狀態。

+0

任何不想使用'react-router'的好理由? –

回答

1

編輯

看起來onbeforeunload是你想要什麼:檢查這related question,其中包含一個useful demo

另外the MDN docs包含一個有用的例子。


假設你已經有了一些很好的理由不想使用react-router,我就勾勒這樣

它看起來像你捕獲了錯誤事件的JavaScript的方式。你想抓取URL散列的任何改變,所以你應該使用onhashchange。從文檔

例子:

if ("onhashchange" in window) { 
    alert("The browser supports the hashchange event!"); 
} 

function locationHashChanged() { 
    if (location.hash === "#somecoolfeature") { 
     somecoolfeature(); 
    } 
} 

window.onhashchange = locationHashChanged; 

不過,我給react-router一去,因爲你正在開發中的反應。在這種情況下,browserHistory將成爲你的朋友。

+0

我不是路由。我有一個嚮導的應用程序類型,用戶點擊下一個,然後使用ajax獲取下一個數據。因此,這不會在瀏覽器歷史記錄中註冊。如果用戶單擊後退按鈕,所以我不能使用hashChange 所以我沒有窗口的狀態留給我。所以即使我使用history.forward.I將有一個新的狀態,並鬆開那一個所以如果有一些優雅的方式來做到這一點,就像瀏覽器關閉事件一樣。 – dhrDatt

+0

使用反應路由器.. ??這也不能作爲一個選項,因爲應用程序已經建成 – dhrDatt

+0

似乎沒有幫助我。正如我之前提到的,我已經使用過這個事件。並且這不會觸發後退按鈕。它僅在刷新和窗口關閉事件時被觸發。 – dhrDatt