首页 > 解决方案 > 在 React 中确认“返回”的导航

问题描述

单击“后退按钮”时,我一直在尝试向用户显示确认弹出窗口。我正在使用React Router v3,所以我不能使用<Prompt/>React Router v4。

这是我想要实现的目标:

我尝试了几件事:

1) setRouteLeaveHook (React Router v3) React Router v3 文档

  componentDidUpdate() {

  ...
  if (isDirty)  // denoting that there is unsaved work
    this.props.router.setRouteLeaveHook(
      this.props.route,
      () => { return 'Unsaved data will be lost' }
    );
  }

2) 'beforeunload' 和 'popstate'

  componentDidUpdate() {

  ...
    if (isDirty)  // denoting that there is unsaved work
      window.addEventListener('beforeunload', this.handleBeforeUnload);
      window.addEventListener('popstate', this.handleOnPopState);
    }
  }

  handleBeforeUnload = e => {
    e.preventDefault();
    const msg = 'Are you sure?';
    e.returnValue = msg;
    return msg;
  }

  handleOnPopState = e => {
    e.preventDefault();
    // how can I prevent here?
  }

防止用户意外导航的最佳方法是什么?任何帮助或建议表示赞赏!

ps 我无法升级到 React Router v4

标签: javascriptreactjsreact-router

解决方案


如果有人遇到同样的问题,请参考我的解决方案:

检测用户离开页面


推荐阅读