场景是我在一个页面上,例如http://example.com/order-confirmation之前的 URL 是/payment。现在,当用户按下后退按钮时,我想将他们重定向到主页,即 URL '/',但它会返回到/payment 页面。
我正在使用 react("^15.1.0")
和 react-router("^2.4.1")
和 react-router-redux("^ 4.0.4")
在我的应用程序中。
我尝试在 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>
);
有什么办法可以覆盖这种行为吗? 请建议... 预先感谢:)
最佳答案
你能试试这个代码吗?
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>
)
}
}
关于javascript - 点击浏览器后重定向到不同的 URL - Reactjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42436794/