首页 > 解决方案 > 单击确定时如何向 React Router 的提示添加功能?

问题描述

我正在做一个多步骤表单,我想防止用户在此过程中离开。这个想法是,如果用户在执行该过程时尝试离开,则向他们显示确认消息,如果他们确认,则将他们重定向到主页,否则留在当前页面。

目前我正在使用来自 React 路由器的 < Prompt/>

<Prompt when={isLeaving} message={"Changes will be lost"}/>

这会显示确认信息,因此如果用户接受,我想将用户重定向到主页。

我也尝试了事件监听器,我几乎完成了它。唯一的问题是它只检测popstates。

useEffect(() => {    
    if(!popEventListnerAdded){
      window.addEventListener('popstate', handleBackButton, false);
      popEventListnerAdded = true;
    }    
  }, []);
const handleBackButton = event => {
      var r = window.confirm("You will need to begin the process again are you sure?");
      if (r === true) {
          // Call Back button programmatically as per user confirmation.
          history.push("/Home"); 
      } else {
          // Stay on the current page.          
          history.push(location.pathname)                  
      }              

  }

当用户在 < Prompt /> 上单击“确定”时,有什么方法可以添加功能以便我可以重定向它们?

非常感谢!

标签: javascriptreactjsreact-reduxreact-router

解决方案


推荐阅读