使用JSZIP与useState解压文件:状态更新异常仅加载最后一个文件
问题解决:ZIP文件仅加载最后一个文件到Dropbox克隆项目
问题原因
zipEntry.async("blob")是异步操作,forEach循环会快速完成所有迭代,但每个then回调执行时,引用的fileList都是循环启动时的初始值。这意味着每次更新都是将新文件添加到旧的数组副本中,最终只有最后一次更新会覆盖之前的结果,导致仅保留最后一个文件。
解决方案
方案1:一次性等待所有文件处理完成后更新
先收集所有异步操作的Promise,等待全部完成后再批量更新文件列表,避免多次基于旧状态更新:
const filePromises = []; zipContent.forEach((relativePath, zipEntry) => { const filePromise = zipEntry.async("blob").then(blob => { const newFile = new File([blob], relativePath, { type: blob.type }); return { id: nanoid(), file: newFile }; }); filePromises.push(filePromise); }); Promise.all(filePromises).then(newFiles => { updateFileList([...fileList, ...newFiles]); });
方案2:使用函数式更新(适用于React等支持函数式状态更新的框架)
如果updateFileList是类似React setState的方法,可以传入一个函数,该函数接收最新的状态值作为参数,确保每次更新都基于当前最新的文件列表:
zipContent.forEach((relativePath, zipEntry) => { zipEntry.async("blob").then(blob => { const newFile = new File([blob], relativePath, { type: blob.type }); updateFileList(prevList => [...prevList, { id: nanoid(), file: newFile }]); }); });
内容的提问来源于stack exchange,提问作者JJacob
相关产品推荐
相关产品推荐

