You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Antd Upload组件使用fileList与customRequest时status无法变为done求助

Antd Upload受控模式下customRequest后status无法切换为done的解决方案

当你给Antd Upload同时设置fileList(受控模式)和customRequest时,组件不会自动更新文件状态——因为受控模式下,文件列表的完全控制权在你手里。调用onSuccess后,组件只会触发onChange,但不会主动修改你维护的fileList,所以你看到的info.file.status一直停留在uploading。

解决方法很直接,在onChange里根据Antd返回的info来更新你的fileList,而非直接替换成自定义数组:

  1. 基于info.fileList(Antd处理后的临时文件列表)更新状态,保证文件的uid和基础信息与组件内部一致;
  2. 当文件状态变为done时,给对应文件添加url等自定义字段即可。

修改后的代码如下:

export default function App() {
  const [fileList, setFileList] = useState([]);

  const onUploadChangeHandler = (info) => {
    console.log("onchange", info);
    let updatedFileList = [...info.fileList];
    
    if (info.file.status === "uploading") {
      console.log("uploading");
      // 上传中直接用Antd返回的临时列表更新状态
      setFileList(updatedFileList);
    }
    
    if (info.file.status === "done") {
      console.log("done", info);
      const Location = "https://img.freepik.com/free-photo/purple-osteospermum-daisy-flower_1373-16.jpg?w=2000";
      // 找到当前完成上传的文件,更新状态和自定义字段
      updatedFileList = updatedFileList.map(file => {
        if (file.uid === info.file.uid) {
          return {
            ...file,
            status: "done",
            url: Location,
            name: decodeURI(Location).slice(decodeURI(Location).indexOf("uqid") + 5)
          };
        }
        return file;
      });
      setFileList(updatedFileList);
    } else if (info.file.status === "error") {
      console.log("error", info);
      // 错误状态同样基于临时列表更新
      setFileList(updatedFileList);
    }
  };

  const customRequestHandler = (info) => {
    console.log("customReq", info);
    const { onSuccess } = info;
    // 模拟异步上传流程,实际场景替换为真实接口调用
    setTimeout(() => {
      onSuccess();
    }, 1000);
  };

  return (
    <div className="App">
      <Form layout="horizontal" form={form3} onFinish={onFinishHandler}>
        <div className="textarea_row">
          <Form.Item label="Passport Photo" name="passport_photo">
            <Upload
              multiple={false}
              className="upload-list-inline"
              customRequest={customRequestHandler}
              fileList={fileList}
              maxCount={1}
              onChange={onUploadChangeHandler}
            >
              <Button icon={<UploadOutlined />}>Upload</Button>
            </Upload>
          </Form.Item>
        </div>
      </Form>
    </div>
  );
}

关键修改点:

  • 不再直接创建全新数组替换fileList,而是基于info.fileList修改,保证文件标识uid的一致性;
  • 上传完成时通过map匹配对应文件,更新其status为done并补充自定义字段;
  • 上传中和错误状态也同步基于临时列表更新,确保组件状态与你的fileList完全同步。

这样修改后,调用customRequest里的onSuccess后,onChange就能正确识别到文件状态变为done,同时fileList也会同步更新。

内容的提问来源于stack exchange,提问作者Abhishek Rawat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 17:21:07