2016-06-09 29 views
0

我幾個小時前問了一個question,並且一切正常。 但問題是,當我在例如第三步中單擊徽標時,我將其重定向到第二步以取代主頁。重定向到具有響應路由器的主頁

任何想法如何避免這一點,當我點擊標識,它將我重定向到主頁,無論我在哪一步。

回答

0

基本上,routerWillLeave鉤子現在總是會在你做一些會導致路由改變的事情中立即開始。由於您只需要在步驟之間導航時使用此特殊行爲,因此可以添加某種flag變量以確定是否需要「正常」行爲。

試試這個:

routerWillLeave = (nextLocation) => { 
    if (this.state.step > 1 && this.flag) { 
    this.setState({step: this.state.step-1}); 
    this.flag = false; // <-- reset the flag. 
    return false; 
    } 
    this.flag = false; // <-- reset the flag. 
} 

我加入了&& this.flag到你的代碼,這意味着step需要大於1個flag需求是true爲了step降低。

要實際設置標誌,只要點擊改變step的按鈕就將其設置爲true。

onButtonClick(name, event) { 
    event.preventDefault(); 
    this.flag = true; // <-- We clicked on button; set flag to true 
    switch (name) { 
    case "stepFourConfirmation": 
     this.setState({step: 1}); 
     break; 
    case "stepTwoNext": 
     this.setState({step: 3, errors: {}}); 
     break; 
    case "stepThreeFinish": 
     this.setState({step: 4}); 
     break; 
    default: 
     this.setState({step: 2, errors: {}}); 
    } 
} 
+0

的問題是,如果我在接下來點擊標誌被設置爲true,我在第二個步驟。當我點擊徽標時,該標誌仍​​然爲true,'routerWillLeave'將執行if語句,因爲該步驟大於1並且該標誌爲true,並且將我重定向到上一步。 – Boky

+0

你說得對。標誌的重置需要移動一點。我會更新代碼。 – Chris

+0

同樣的問題。 – Boky

0

也許你驗證,如果nextLocation是「/」並返回true:

componentDidMount =() => { 
    this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave); 
    //or this.context.router, depending on your app 
} 

routerWillLeave = (nextLocation) => { 
    if(nextLocation === '/') { 
    return true; 
    } 

    if (this.state.step > 1) { 
    this.setState({step: this.state.step-1}); 
    return false; 
    } 
} 
+0

不,它不工作。問題是一樣的。 – Boky