Forráskód Böngészése

fix[pc-components]: 修复上传破损图片导致阻塞

chenlei 1 éve
szülő
commit
0ea90acf02

+ 27 - 4
packages/pc-components/src/components/DageUpload/index.tsx

@@ -5,7 +5,8 @@ import {
   PlusOutlined,
   UploadOutlined,
 } from "@ant-design/icons";
-import { FC, useContext, useMemo, useState } from "react";
+import { updateFileList } from "antd/es/upload/utils";
+import { FC, useContext, useEffect, useMemo, useRef, useState } from "react";
 import { requestByPost } from "@dage/service";
 import { RcFile, UploadFile, UploadProps } from "antd/es/upload";
 import {
@@ -46,6 +47,11 @@ export const DageUpload: FC<DageUploadProps> = ({
   ...rest
 }) => {
   const context = useContext(DageUploadContext);
+  // 内部维护 mergeFileList
+  // 修复 reat18 受控模式下批量更新导致状态异常
+  const _mergedFileList = useRef<
+    (UploadFile<any> | Readonly<UploadFile<any>>)[]
+  >([]);
   const [previewOpen, setPreviewOpen] = useState(false);
   const [previewImage, setPreviewImage] = useState("");
   const [previewTitle, setPreviewTitle] = useState("");
@@ -77,6 +83,11 @@ export const DageUpload: FC<DageUploadProps> = ({
     }
   }, [dType]);
 
+  useEffect(() => {
+    if (!value) return;
+    _mergedFileList.current = value;
+  }, [value]);
+
   const beforeUpload = (file: RcFile) => {
     let pass = false;
     let passFileType = false;
@@ -149,14 +160,26 @@ export const DageUpload: FC<DageUploadProps> = ({
         file.status = "error";
       } else if (isPictureCard && file.originFileObj) {
         // 如果是图片获取图片宽高
-        // @ts-ignore
-        file.imgAttrs = await getImageSize(file.originFileObj);
+        try {
+          // @ts-ignore
+          file.imgAttrs = await getImageSize(file.originFileObj);
+        } catch (err) {
+          // 图片加载失败
+          file.status = "error";
+        }
       }
 
       context?.handleUploadingFileNum("uploaded");
     }
+
+    if (_mergedFileList.current.length > newFileList.length) {
+      _mergedFileList.current = newFileList;
+    } else {
+      _mergedFileList.current = updateFileList(file, _mergedFileList.current);
+    }
+
     onChange?.(
-      newFileList.map((i) => ({
+      _mergedFileList.current.map((i) => ({
         ...i,
         dType,
       })),

+ 4 - 2
packages/pc-components/src/components/DageUpload/utils.ts

@@ -1,6 +1,8 @@
-import { RcFile } from 'antd/es/upload';
+import { RcFile } from "antd/es/upload";
 
-export async function getImageSize(file: RcFile): Promise<{ width: number; height: number }> {
+export async function getImageSize(
+  file: RcFile
+): Promise<{ width: number; height: number }> {
   return new Promise((resolve, reject) => {
     const img = new Image();