您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

react怎么实现路由跳转前确认

2025/3/15 14:37:31发布31次查看
react实现路由跳转前确认功能的方法:1、通过“import { modal } from 'antd';”方法引入“antd”;2、使用antd的“modal.confirm”实现弹框;3、设置form表单内容即可。
本教程操作环境:windows10系统、react18.0.0版、dell g3电脑。
react怎么实现路由跳转前确认?
react-router 跳转前确认prompt使用
需求
页面切换的时候,会遇到这样的需求:切换时需要判断内容区域编辑后是否保存了, 若没保存,则弹出提示框,提示保存。
官网示例
react router中的prompt可以实现这样的功能。
prompt示例:https://reactrouter.com/web/example/preventing-transitionsprompt文档:https://reactrouter.com/core/api/prompt
/** when:是否启用 *//** message:string | func */// 示例1<prompt when={formishalffilledout} message="are you sure you want to leave?"/>// 示例2<prompt message={(location, action) => { if (action === 'pop') { console.log("backing up...") } return location.pathname.startswith("/app") ? true : `are you sure you want to go to ${location.pathname}?` }}/>
实现
我们项目的技术栈umi+antd+react
弹框用的antd的 modal.confirm
import react, { useeffect, usestate } from 'react';import { modal } from 'antd';import { useboolean } from '@umijs/hooks';// umi里封装了该组件// 或者 import { prompt } from "react-router-dom";import { useparams, history, prompt } from 'umi';import { exclamationcircleoutlined} from '@ant-design/icons';import { isequal } from '@/utils/utils';import { forminstance } from 'antd/lib/form';export default function baseinfo() { const { id } = useparams<{ id: string }>(); // 保留原始数据 const [orgindata, setorigin] = usestate({}); // 修改后的数据 const [modifydata, setmodify] = usestate({}); // 是否启用prompt const { state, settrue, setfalse } = useboolean(false); // 还原信息 useloading是自己封装的hooks const [isfetching, fetchinfo] = useloading(getservicegroupdetail); useeffect(() => { (async () => { try { if (id !== '0') { const info = await fetchinfo(id); setorigin({ ...info }); setmodify({ ...info }); } } catch (e) { console.error(e); } })(); }, [id]); useeffect(() => { if (isequal(orgindata, modifydata)) { setfalse(); } else { settrue(); } }, [orgindata, modifydata]); const nextstep = (pathname?: string) => { setfalse(); pathname && settimeout(() => { history.push(pathname); }); }; return ( {/* 这里原来放的form表单内容 */} {routerwillleave(state, form, nextstep)} );}function routerwillleave( isprompt: boolean | undefined, forminstance: forminstance, // 保存,我这个页面是form表单 nextstep: (pathname?: string) => void) { return ( <div> <prompt when={isprompt} message={(location) => { if (!isprompt) { return true; } modal.confirm({ icon: <exclamationcircleoutlined />, content: '暂未保存您所做的更改,是否保存?', oktext: '保存', canceltext: '不保存', onok() { forminstance?.submit(); nextstep(location.pathname); }, oncancel() { nextstep(location.pathname); } }); return false; }} /> </div> );}
推荐学习:《react视频教程》
以上就是react怎么实现路由跳转前确认的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product