javascript - 点击浏览器后重定向到不同的 URL - Reactjs

标签 javascript reactjs react-router react-router-redux

场景是我在一个页面上,例如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/

相关文章:

javascript - 如果刷新页面则找不到 React Router URL - 创建 React App

javascript - react 路由器不渲染组件

javascript - 如何删除表格中两张纸上的同一行?

javascript - 在html中接受输入作为Json并发送http请求

reactjs - React-Redux:调度时无限循环

reactjs - 在 ReactJS 中屏蔽密码输入

html - 在 react 中如何自动打开另一个页面?

reactjs - 如何在react-router onEnter中等待状态变化?

javascript - Firebase 中正确的数据结构

javascript - 尝试使用 href 运行 javascript 进行验证