在Reaction Router V6中,如何在离开页面/路由之前检查表单是否脏 [英] In React Router v6, how to check form is dirty before leaving page/route
本文介绍了在Reaction Router V6中,如何在离开页面/路由之前检查表单是否脏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我正在使用的包版本。
React version - 16.13.1
react-router-dom version - 6.0.0-beta.0
react-redux version 7.2.0
Material UI version 4.11.0
当用户尝试离开当前页面时,检查表单isDirty
(已更改)的最佳方式/方式是什么?如果表单isDirty
。您确定要离开吗?isDirty
(&Q;)。
我将从useEffect()
中提取数据,并使用重复数据减少器呈现UI。
我是否应该声明一个变量以保留原始提取的数据以进行脏检查?
这就是我正在做的事情,可它不能正常工作。
Component.js
useEffect(() => {
props.fetchUserInfo();
})
action.js
export function fetchUserInfo() {
return (dispatch) => {
dispatch({type: USER_INITIALSTATE, {Name: 'abc', Age: 20}}
)
}
}
userReducer.js
const initialState = {
processing: false,
success: false,
fail: false,
Profile: {}
}
let oriState;
let State;
const UserReducer = (state = initialState, action) => {
if (action.type === USER_INITIALSTATE) {
oriState = {Profile: action.data};
State = {...state, Profile: action.data};
return {...state, Profile: action.data};
} else if (action.type === OTHERS_ACTION) {
//update field change
return {...state, xxx}
}
}
export const userIsDirty = state => {
if (oriState && State) {
return JSON.stringify(oriState.Profile) !== JSON.stringify(State.Profile);
}
return false;
};
export default UserReducer;
因此,在我的组件中,我调用userIsDirty
以返回isDirty布尔值,但是我还没有想出如何捕获Leave Page事件并将其用作触发器来执行脏表单检查。
那么如何检测离开当前页面呢?我在useEffect return(组件umount)上尝试了一些操作,但是道具没有获得更新后的INITIALSTATE状态(这意味着我将获得PROFILE:{}),因为它只运行一次,但是如果我添加useEffect可选数组参数,我会得到一个无限循环(可能我设置错了?)。
useEffect(() => {
props.fetchUserInfo();
return () => {
console.log(props); //not getting initial state object
};
}, []);
我做这件事的方式正确吗?我错过了什么?是否有更好/正确的解决方案来实现我想要的?
已更新
谢谢@gdh,useBlocker
就是我想要的。我正在使用它弹出确认对话框。
我将分享我完整的代码包装箱,我相信这可能会对将来的某个人有所帮助。
show confirmation dialog by using useBlocker
推荐答案
此答案使用路由器V6。
- 您可以使用usePrompt。
- usePrompt将在您转到另一个路由(即装载上)时显示确认模式/弹出窗口。
- 尝试关闭浏览器时显示带有消息的常规警报。它在内部处理卸载前
usePrompt("Hello from usePrompt -- Are you sure you want to leave?", isBlocking);
- 您可以使用useBlocker
- useBlocker将在用户尝试导航离开(即卸载时)时直接使用挡路
- 尝试关闭浏览器时显示带有消息的常规警报。它在内部处理卸载前
useBlocker(
() => "Hello from useBlocker -- are you sure you want to leave?",
isBlocking
);
- 您也可以使用beforeunload。但是你必须做你自己的逻辑。See an example here
这篇关于在Reaction Router V6中,如何在离开页面/路由之前检查表单是否脏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文