【问题标题】:Preventing the React Router's current path from changing whenever the confirmation is false每当确认为假时,防止 React Router 的当前路径发生变化
【发布时间】:2019-06-20 05:33:28
【问题描述】:

当我点击浏览器的后退按钮然后点击确认框中的“取消”按钮时,我无法阻止路径重定向。

componentDidMount() {
    window.addEventListener('popstate', this.quit);
}

quit = () => {
    if(confirm('Quit?')) {
        location.assign('/'); // Refreshes the browser then redirects to the homepage
        history.pushState(null, null, null); // Clears the previous history
    } else {
        // What to do if the user clicks "Cancel"?
    }
}

我尝试了return false,但它仍在将应用程序重定向到主页(但没有刷新页面)。我尝试过其他解决方案,例如 location.pathname = '/currentPathname'location.replace('/currentPathname'),但由于这些解决方案重新加载浏览器,它会显示 Cannot get /currentPathname,因为 React Router 不需要重新加载。 <Prompt /> 组件也没有解决问题,因为它没有我可以执行上面代码的函数道具。

【问题讨论】:

  • 尝试将事件监听器改为beforeunload而不是popstate
  • 更糟。没有确认和刷新页面
  • 试试这个页面上的建议:stackoverflow.com/questions/32841757/…
  • 实现初始目标的最佳选择是使用<Prompt /> 来防止不必要的导航。我不确定你为什么需要执行那段特定的代码,因为浏览器通常会处理这个问题。我还尝试创建了一个 CodeSandbox:codesandbox.io/s/m3o0wv1w29
  • 问题解决了! <Prompt />componentDidMountcomponentWillUnmount 的帮助下解决了这个问题。谢谢大家!

标签: reactjs react-router browser-history


【解决方案1】:

实现初始目标的最佳选择是使用 防止不必要的导航。您还可以像这样同时使用componentDidMountcomponentWillUnmount 受益:

componentDidUpdate = () => {
    //Prompt Browser Refresh / Close
    if ("Your Condition" || true) {
      window.onbeforeunload = () => true;
    } else {
      window.onbeforeunload = undefined;
    }
};

componentDidMount() {
    this.setState({ shouldPrompt: true });
    this.props.history.listen((location, action) => {
      console.log(location);
      if (action === "POP") {
      }
    });
}

...

render() {
    return (
        <Prompt
          when={shouldPrompt}
          message="You have unsaved changes, are you sure you want to leave?"
        >
          <Switch>
            <Route path="/" component={Page1} exact />
            <Route path="/page2" component={Page2} exact />
          </Switch>
        </Prompt>
    )
}

【讨论】:

  • 我以前看过这个技巧。虽然很有帮助
  • @jstarnate 我把它写成一个答案,你可以用它来标记问题已解决
猜你喜欢
  • 2016-10-20
  • 2018-11-03
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
相关资源
最近更新 更多