2017-02-15 58 views
2

在反应路由器documentationonEnter钩他们指定如何处理,但onLeave没有例子。我的问题是如何确认用户想要正确离开页面。在反应路由器是onEnter是onLeave

根据以下两种情况给出的代码,无论用户点击cancel还是ok,它都会离开页面。但OnEnter钩按逻辑工作正常。

const checkEnterAbout = (nextState, replace, callback) => { 
    if(!confirm('do you want to enter really!!!')){ 
     replace(`/`); 
    }else{ 
     callback(); 
    } 

} 

const checkLeaveAbout = (prevState) => { 
    console.log(prevState); 
    return confirm("Are you sure you want to leave this page"); 
} 

<Route path="/about" component={About} onEnter={checkEnterAbout} onLeave={checkLeaveAbout} /> 

另外当我试着withRouter确认指南。它给我的

Failed prop type: Invalid prop `component` supplied to `Route`. 
    in Route 
+0

您是否想在** **的任何页面的用户离开的确认?或者只是关于页面? – samvv

+0

只是关于页面 – owaishanif786

回答

2

错误有一个叫routerWillLeave钩,这里有一个例子:

https://github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md

+0

我已经尝试,但没有运气检查编辑答案 – owaishanif786

+0

后更改导出默认与路由器(约)为module.exports = withRouter(关于);这是工作。想知道为什么onLeave和onEnter api界面不一样。一个是通过componentDidMount工作,另一个是通过使用onEnter! – owaishanif786