2016-04-28 42 views
0

因此,我正在將我們的反應路由器從0.13升級到2.3,但我遇到了問題。在0.13,以防止過渡的用戶,如果說他們有未保存的形式變化,我將在靜做到這一點:離開過渡掛鉤反應路由器2.3

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())),如果用戶單擊確定進行轉換並丟失更改。

如何才能完成willTransitionFrom在2.3中的0.13?

回答

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

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> 
    } 
}); 
+0

的問題是從什麼我用'setRouteLeaveHook'和'listenBefore'看到了(而'setRouteLeaveHook'給出了關於使用'listenBefore'的警告)我不能執行自定義代碼,這取決於它們是否點擊繼續或不是(這需要是自定義取決於它發生什麼頁面,所以我不能在browserHistory上設置通用代碼)。 – ryanzec