我正在尝试获取React Native中项目列表的下载进度。但在我目前的方法中,进度计算不正确。我正在使用react原生fs下载文件。
const onPressDownload = async () => {
const files = [
'https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4',
'https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_640_3MG.mp4',
'https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_1280_10MG.mp4',
'https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_1920_18MG.mp4',
... // This is a dynamic list
];
const promises = [];
let index = 1;
let totalLength = 0;
let downloadLength = 0;
let progress = 0;
for (const file of files) {
const promise = RNFS.downloadFile({
fromUrl: file,
toFile: `${RNFS.DocumentDirectoryPath}/download_${index}.mp4`,
begin: (res) => { totalLength += res.contentLength; },
progress: (res) => {
downloadLength += res.bytesWritten;
progress = (downloadLength / totalLength);
console.log(progress);
},
});
promises.push(promise);
index++;
}
Promise.all(promises);
};
我在这里做错了什么?
->你做得对,但有一个常见的错误如下。。。
->在RNFS.downloadFile之前插入wait关键字,因为它是异步
->一切都可能顺利进行。