所以我正在将我们的反应路由器从0.13升级到2.3但是我遇到了一个问题。在0.13中,为了防止用户过渡,如果说他们有未保存的表单更改,我会在静态中执行此操作:
willTransitionFrom: function(transition) {
if (unsavedChangesStore.hasUnsavedChanges()) {
if (!confirm('You have unsaved changes, are you sure you want to leave this page?')) {
transition.abort();
} else {
this.props.dispatch(unsavedChangesActions.clearUnsavedChanges());
}
}
}
2.3不再使用静态内容。从我的阅读来看,似乎我必须使用的是this.context.router.listenBefore()
但是我开始工作的唯一方法是使用这样的函数:
function(location) {
if (unsavedChangesStore.hasUnsavedChanges()) {
return 'You have unsaved changes, are you sure you want to leave this page?';
}
}
这个问题是,如果用户单击“确定”进行转换并丢失更改,我需要能够运行清理代码(this.props.dispatch(unsavedChangesActions.clearUnsavedChanges())
)。
如何在2.3中完成willTransitionFrom
在0.13中的作用?
答案 0 :(得分:0)
如果不知道您的代码会让您进入的确切方案,请点击此处:
在ES6中:
class Page extends React.Component {
componentWillMount(){
this.context.router.setRouteLeaveHook(
this.props.route,
this.routerWillLeave
)
}
routerWillLeave( nextLocation ){
if (unsavedChangesStore.hasUnsavedChanges()) {
return 'You have unsaved changes, are you sure you want to leave this page?';
}
}
render(){
return <h1>The Page</h1>
}
}
Page.contextTypes = { router: React.PropTypes.object.isRequired }
ES5中的OR
var Page = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
componentWillMount: function(){
this.context.router.setRouteLeaveHook(
this.props.route,
this.routerWillLeave
)
},
routerWillLeave( nextLocation ){
if (unsavedChangesStore.hasUnsavedChanges()) {
return 'You have unsaved changes, are you sure you want to leave this page?';
}
},
render:function(){
return <h1>The Page</h1>
}
});