2017-02-24 96 views
1

這種情況是我在一個頁面上,例如http://example.com/order-confirmation和以前的網址是/付款。現在,當用戶按下返回按鈕時,我想將它們重定向到主頁,即URL'/',但它將返回到/付款頁面。 我在我的應用程序中使用react("^15.1.0")react-router("^2.4.1")react-router-redux("^4.0.4")重定向到不同的網址onClick瀏覽器返回 - Reactjs

我試過在StackOverflow或git上的多個答案,但都是徒勞的。 例如下面我嘗試:

import { push } from 'react-router-redux'; 

<Route 
    path={`${AppPaths.ORDER_CONFIRMATION}/:orderId`} component={OrderConfirmationContainer} onLeave={(prevState) => routeBackHome(store, prevState)} 
    onEnter={routeEntryHandler(store, nonGuestUserValidator)} 
/> 

const routeBackHome = (store, prevState) => { 
    store.dispatch(push(`/`)); 
}; 

我的路線:

export const createRoutes = store => (
<Route path={AppPaths.BASE} component={CheckoutAppContainer} onEnter={CheckoutAppContainer.fetchUserState(store)}> 
<IndexRedirect to={`${AppPaths.BASE}/${AppPaths.BAG}`} /> 
<Route component={CheckoutWizardContainer} onLeave={() => clearNotifications(store)}> 
    <Route 
    path={AppPaths.BAG} component={CartContainer} onLeave={() => clearNotifications(store)} 
    onEnter={() => updateStepNumber(store, 1)} 
    /> 
    <Route 
    path={AppPaths.PAYMENT} component={QuickCheckoutContainer} onLeave={() => clearNotifications(store)} 
    onEnter={checkoutEntryHandler(store, 3)} 
    /> 
</Route> 
<Route 
    path={`${AppPaths.ORDER_CONFIRMATION}/:orderId`} component={OrderConfirmationContainer} 
    onEnter={routeEntryHandler(store, nonGuestUserValidator)} 
/> 
</Route> 
); 

有什麼辦法可以覆蓋這種行爲? 請建議... 在此先感謝:)

+0

你能張貼代碼? – juancab

+0

請參閱編輯的問題。 –

+0

您是否使用中間件將您的BrowserHistory與您的商店同步到您的Redux商店? – juancab

回答

0

你可以試試這個代碼嗎?

class YourComponent extends Component { 
    constructor(props) { 
     super(props); 

     this.onUnload = this.onUnload.bind(this); // if you need to bind callback to this 
    } 

    onUnload(event) { // the method that will be used for both add and remove event 
    const gohome = confirm('go home?') 
    if (gohome === true) { 
     console.log('yay') 
     window.location = 'http://yourhomepage.com' 
    }else { 
     console.log('yes') 
    } 
    } 

    componentDidMount() { 
    window.addEventListener("beforeunload", this.onUnload) 
    } 

    componentWillUnmount() { 
     window.removeEventListener("beforeunload", this.onUnload) 
    } 

    render() { 
    return (
     <div> 
      Try with window location 
     </div> 
    ) 
    } 
} 
+0

它不起作用。仍然會持續網址即付款。 –

+0

其他路線如何? – juancab

+0

@juancab:相似,但我認爲這不重要... –

0

嘗試以下操作:

import { browserHistory } from 'react-router' 

import { push } from 'react-router-redux'; 

<Route 
    path={`${AppPaths.ORDER_CONFIRMATION}/:orderId`} component={OrderConfirmationContainer} onLeave={(prevState) => routeBackHome(store, prevState)} 
    onEnter={routeEntryHandler(store, nonGuestUserValidator)} 
/> 

const routeBackHome = (store, prevState) => { 
    browserHistory.push('/'); 
}; 
+0

這也不起作用... –

+0

從'react-router'導入{browserHistory}不起作用。 'react-router'不包含名爲'browserHistory'的導出。 –

相關問題