2016-06-17 219 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