React antd form表单未保存跳转页面提示
需求是:
表单编辑后没保存,跳转其他页面需要提示未保存,保存就继续form的submit,反之就是关闭弹窗,再切换菜单正常跳转路由。
关键代码如下:
const [initialFormValues, setInitialFormValues] = useState({});
const initialFormValuesRef = useRef(initialFormValues);
const handleGeneralForm = () => {
const {
avatar = '',
tenantName = '',
timeZoneId = '',
tenantEmail = '',
webSite = '',
address = '',
} = currentUserTenant;
form.setFieldsValue({
avatar,
tenantName,
timeZoneId,
tenantEmail,
webSite,
address,
});
setInitialFormValues(form.getFieldsValue());
};
useEffect(() => {
loadGetAllTimeZone();
handleGeneralForm();
initialFormValuesRef.current = form.getFieldsValue();
}, []);
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
const [blockOpen, setBlockOpen] = useState(false);
const deleteAvatar = () => {
form.setFieldsValue({
avatar: '',
icon: '',
});
setDeleteConfirmOpen(false);
};
useEffect(() => {
const unblock = history.block(({ location, action }) => {
if (action === 'PUSH' || action === 'REPLACE') {
const pathname = location.pathname;
unblock();
const isFormChanged = isEqual(form.getFieldsValue(), initialFormValuesRef.current);
if (!isFormChanged) {
setBlockOpen(true);
} else {
history.push({
pathname: pathname,
search: location.search,
});
}
}
});
return () => {
unblock();
};
}, []);
import { isEqual } from 'lodash';
const isFormChanged = isEqual(form.getFieldsValue(), initialFormValuesRef.current);
这就是个对比
原文地址:https://blog.csdn.net/qq_36279445/article/details/140550422
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!