网站显示搜索框,云南昆明网站设计,新泰营销型网站建设,flash网站建设个人简介在 react umi 中对离开页面的行为进行自定义弹窗拦截控制。以下为可选的方案分析。
wrapper
首先#xff0c;因为项目框架是 umi#xff0c;最先想到了 umi 路由的 wrapper 装饰器#xff0c;但仔细一想又不太对#xff0c; wrapper 争对于跳转到某个特定页面的前置行为…在 react umi 中对离开页面的行为进行自定义弹窗拦截控制。以下为可选的方案分析。
wrapper
首先因为项目框架是 umi最先想到了 umi 路由的 wrapper 装饰器但仔细一想又不太对 wrapper 争对于跳转到某个特定页面的前置行为而我需要是离开某个页面行为的拦截该思路 Pass。
beforeunload
其次想到的是原生的 windows 事件beforeunload
useEffect(() { window.addEventListener(beforeunload, (event: BeforeUnloadEvent) { event.preventDefault(); event.returnValue ; })
}, [])不过这样做只能拦截到刷新行为同时还是浏览器默认的那个巨丑的弹框Pass。
history.block
最后umi 提供了 history类似 react-router v4 的 useHistory利用其 block 方法可以实现我们的需求
需求概述当提交表单后页面处于加载等待结果的过程中需要拦截用户离开页面的行为通过弹框警告其需要等待过程完成才能离开页面仅提供 确定/知道 按钮不提供继续按钮。
思路通过 history.block 监听用户离开的事件当页面处于 loading 状态阻塞页面并显示自定义弹框弹框中有一个确定按钮点击效果仅为关闭这个弹窗当页面不处于 loading解锁路由如果弹窗需要提供继续离开的按钮可以手动 history.push(next) 到之前触发 block 时获取到的下一个路由next伪代码
import { Button, Modal } from antd;
import { history } from umijs/max;const [loading, setLoading] useState(false); // 某容器加载
const [blockOpen, setBlockOpen] useState(false);
const [unblock, setUnblock] useStateFunction();
const [next, setNext] useState();useEffect(() { if (loading) { setUnblock(history.block(({location}) { setNext(location.pathname);setBlockOpen(true);return false; }))} else {unblock?.();
}, [loading, unblock])const Leave () Button onClick{() {unblock?.();if (next) {history.push(next);}
}}Buttonexport default function Reconc() {return(/** 上面应当有一个容器绑定loading通过某些控件控制器其加载状态 */Modal open{blockOpen} footer{Button typeprimary onClick{() setBlockOpen(false)}Button}span操作尚未完成请等待操作结束再离开页面span/Modal/)
}
基本实现方案就是这样Bingo