Antd Upload组件异常求助:PDF加载无限/图片文字变红
Antd Upload 组件状态异常修复方案
问题根源分析
Antd Upload 组件的文件显示状态完全依赖 handleChange 回调中维护的文件对象状态值:
- PDF 进度条无限加载:上传成功后未将文件的
status标记为'done',组件持续判定为上传中状态 - 图片文件名红色:文件上传成功后,
status被错误设置为'error',或未正确处理成功回调的状态更新
修正后的 handleChange 逻辑
以下是适配图片和PDF上传的回调逻辑,核心是根据服务器响应结果,精准更新文件状态:
const handleChange = (info) => { // 上传中状态:Antd 会默认处理进度,无需额外操作(如需自定义进度可在此扩展) if (info.file.status === 'uploading') { return; } // 上传完成分支:根据服务器响应确认最终状态 if (info.file.status === 'done') { const res = info.file.response; // 请根据实际后端接口的成功判定规则调整(比如code=200或success=true) const isSuccess = res?.code === 200 || res?.success; const updatedFile = { ...info.file, status: isSuccess ? 'done' : 'error', error: isSuccess ? null : new Error(res?.msg || '上传失败') }; // 更新组件维护的文件列表(假设用 useState 管理 fileList) setFileList(prevList => { const targetIndex = prevList.findIndex(item => item.uid === info.file.uid); const newList = [...prevList]; newList[targetIndex] = updatedFile; return newList; }); } // 上传失败分支:直接标记错误状态并提示 if (info.file.status === 'error') { message.error(`${info.file.name} 上传失败`); } };
关键注意事项
- 手动维护 fileList:必须通过状态管理工具(如 useState)维护文件列表,确保每个文件的
status与实际上传结果完全匹配 - 适配后端接口:根据你的服务器返回结构调整成功判定逻辑,不要硬套示例中的规则
- 统一状态处理:图片和PDF的成功状态都要设置为
'done',避免不同文件类型的状态差异
组件使用示例
确保 Upload 组件绑定正确的状态和回调:
<Upload fileList={fileList} onChange={handleChange} action="/your-upload-api" accept="image/*,.pdf" > <Button icon={<UploadOutlined />}>选择文件</Button> </Upload>
内容的提问来源于stack exchange,提问作者Esther
相关产品推荐
相关产品推荐

