我正在实现文件上传,当上传正在进行时,它有一个与之关联的进度条。其初始状态维护如下:
const [file, setFile] = useState({ file: null, error: '', status:0});
我一直在轮询上传 api,直到后端向我发送完成状态,然后我将文件状态设置为 { file: File, error: '', status:100 } 然后导致消息显示为“文件完成” '.
我想开始轮询可能是从60一直到100.但是这里进度卡在60.
我如何模拟这个投票? 下图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});
setMock(mock=> mock +10);
}
}, 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) {
setTimeout(() => {
if (mock < 100) {
setFile({ file, error: '', status: mock });
setMock((mock) => mock + Math.floor(Math.random() * 10) + 1);
onUpload(file);
} else {
setFile({ file, error: '', status: 100 });
}
}, 100);
}
};