如何使用 setTimeout 模拟虚假进度?

问题描述 投票:0回答:1

我正在实现文件上传,当上传正在进行时,它有一个与之关联的进度条。其初始状态维护如下:

const [file, setFile] = useState({ file: null, error: '', status:0});

我一直在轮询上传 api,直到后端向我发送完成状态,然后我将文件状态设置为 { file: File, error: '', status:100 } 然后导致消息显示为“文件完成” '.

但在其中一种情况下,后端不支持轮询。它只是将响应发送为 200,这意味着上传已完成。由于在这种情况下,没有轮询,我必须手动模拟此轮询并设置状态 100 可能是从一个数字开始(比如 60),一直到 100。

我如何模拟这个投票? 下图60后不运行状态

我试过的代码

// defining the initial state
const [file, setFile] = useState({ file: null, error: '', status:0});
const [mock, setMock] = useState(60);


const onUpload = (file) =>{
   // upload api is called
   if(response.status === 200){
      // I have to start polling, may be start from 60;
         const intervalID = setInterval(() => {
         if (mock === 100) {
             clearInterval(intervalID);
         } else {
            setFile({ file, error: '', status: mock});
            const random = Math.floor(Math.random() * (100 - mock + 1)) + mock
            setMock(random);
         }
        }, 100);
   }
}

此代码似乎不起作用,有人可以帮助我吗?

javascript reactjs react-hooks settimeout setinterval
1个回答
0
投票

试试这个,你犯了 2 个错误。 1:您传递的是文件而不是文件,它是实际的文件对象。您应该将其更改为 setFile({ file, error: '', status: mock}); 2:您正在使用 Math.random() 生成模拟和 100 之间的随机数,这有时会导致进度条向后而不是向前移动。为避免这种情况,您可以在每次运行间隔函数时将模拟状态增加固定数量。

const [file, setFile] = useState({ file: null, error: '', status: 0 });
const [mock, setMock] = useState(60);

const onUpload = (file) => {
  // upload api is called
  if (response.status === 200) {
    // start the mock polling
    let intervalID = setInterval(() => {
      if (mock >= 100) {
        clearInterval(intervalID);
        setFile({ file, error: '', status: 100 });
      } else {
        setFile({ file, error: '', status: mock });
        setMock(mock + 5); // increment by a fixed amount
      }
    }, 100);
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.