问题描述
useEffect(() => {
if (window.performance) {
if (performance.navigation.type === 1) {
if (progress.length !== 0) {
if (progress[0].progress !== 100) {
alert('Your video is uploading ! page reload will stop your video upload');
}
}
}
}
}
解决方法
您可以尝试beforeunload
事件。逻辑将在以下几行之内:
window.beforeunload = (e) => {
e.preventDefault()
if (progress.length !== 0) {
if (progress[0].progress !== 100) {
alert('Your video is uploading ! page reload will stop your video upload');
e.returnValue = '';
}
}
};
但是根据在React中的实现方式,您可能会得到一些错误,可以通过遵循https://stackoverflow.com/a/39094299或使用react-beforeunload库进行修复
import { useRef,useEffect } from 'react';
const useUnload = fn => {
const cb = useRef(fn);
useEffect(() => {
const onUnload = cb.current;
window.addEventListener("beforeunload",onUnload);
return () => window.removeEventListener("beforeunload",onUnload);
},[cb]);
};
export default useUnload;
const MyComponent = () => {
useUnload(e => {
e.preventDefault();
e.returnValue = '';
});
return (
<div>
Some content
</div>
);
};