【发布时间】:2021-07-29 07:31:02
【问题描述】:
我试图在从后端获取 API 时显示进度条。它似乎有效,但是有几个我无法解决的问题。 a) 进度条从 0 变为 100,并且不显示任何进度,因为 onDownloadProgress 仅被触发一次。 b) 我想要 setTimeout,因为有时加载 API 的速度非常快,以至于在应用程序开始运行后进度条就消失了。我天真地认为 setTimeout 可以防止这个问题,因为我可以在获取 API 完成后暂停整个过程。由于 setTimeout 永远不会被触发,因此加载保持为真并且进度条永远不会消失。
const [loading, setLoading] = useState(false);
const [progress, setProgress] = useState(0);
useEffect(() => {
// grab rooms from back end
fetchRooms();
}, []);
const fetchRooms = async () => {
try {
setLoading(true);
const res = await axios.get(`${ENDPOINT}/api/rooms`, {
onDownloadProgress: (progressEvent) => {
setProgress(Math.round((progressEvent.loaded * 100) / totalLength));
if (progress === 100) {
setTimeout(() => {
console.log("load finished!////////");
setLoading(false);
}, 2000);
}
},
});
setRooms(res.data);
// having setLoading here dose not work as progress bar disappears right after application starts to run if loading is too fast
// setLoading(false);
} catch (err) {
console.log(err);
setProgress(0);
}
};
【问题讨论】:
标签: javascript reactjs ajax axios progress-bar