一、在做一个管理端平台应用时,有个需求,在新建页面离开时要触发一个确认离开弹框提醒用户离开后所编辑内容不会被保存。

image

二、 页面情况如下,可以通过点击一级和二级路由离开当前新建页面,也能通过顶部箭头返回到上一个页面。而且点击保存和发布的跳转是不需要被监听的,那怎么实现呢。

image
image

三、实现代码。

  const unblock = useRef(); // 存放取消阻止导航的方法
  const pathRef = useRef(null); // 存放跳转的pathname

  // 路由拦截弹窗
  useEffect(() => {
    unblock.current = history.block((location, action) => {
      pathRef.current = location?.location?.pathname; 
      setIsExitModalOpen(true); // 打开弹框
    });
  }, []);
  
/*
  在保存和发布的处理函数中调用unblock.current(),因为这里的导航我们不需要阻止,
  正常跳转即可,然后我们通过history.push(pathRef.current)就行了
*/
posted on 2025-03-23 02:19  九零菜菜  阅读(45)  评论(0)    收藏  举报