当用户从React JS上传到服务器时尝试重新加载页面时,如何向用户显示警报?

问题描述

基本上,我想防止在文件上传过程中刷新手动页面

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>
  );
};