前言
大家好 我是歌谣 在日常的学习生活中 我们会遇到各种各样的问题 今天在工作中就遇到了多个文件上传的时候会调用多次接口 感谢群友的帮助 想加入前端巅峰交流群可以私信我
原因
一开始不知道原因 后来在群友的帮助下 最后知道了原因
是onChange的原因
上传中、完成、失败都会调用这个函数
思路解答
群友给的demo
import "./styles.css";
import React, { useState, useEffect, useRef } from "react";
import { Button, Upload } from "antd";
import { UploadOutlined } from "@ant-design/icons";
export default function App() {
const fileState = useRef();
const [uploadFiles, setUploadFiles] = useState([]);
const updateFiles = (function () {
let fileList;
return function (list, setState) {
if (!fileList) {
fileList = list;
setState && setState(list);
}
return {
fileList,
reset() {
fileList = false;
}
};
};
})();
function beforeUpload(_, fileList) {
fileState.current = updateFiles(fileList, setUploadFiles);
return false;
}
const customRequest = () => {
console.log("自定义上传", uploadFiles);
};
useEffect(() => {
if (uploadFiles.length > 0) {
customRequest();
fileState.current.reset();
}
}, [uploadFiles]);
return (
Hello CodeSandbox
Start editing to see some magic happen!
);
}
项目给的demo
upload部分
}>
上传
beforeUpload部分
const fileState: any = useRef();
const [uploadFiles, setUploadFiles] = useState([]);
const updateFiles = (function () {
let fileList: any = null;
return function (list: any, setState: any) {
if (!fileList) {
fileList = list;
setState && setState(list);
}
return {
fileList,
reset() {
fileList = false;
}
};
};
})();
useEffect(() => {
if (uploadFiles.length > 0) {
customRequest();
fileState.current.reset();
}
}, [uploadFiles]);
function beforeUpload(_: any, fileList: any) {
fileState.current = updateFiles(fileList, setUploadFiles);
return false;
}
const [loadingButton,setLoadingButton]=useState(false)
const customRequest = () => {
let formData = new FormData();
uploadFiles.forEach((file: any, index: any) => {
formData.append(`file`, file
);
});
uploadFile("manufacture/cutScheme/batchUploadDrawing", formData).then((res) => {
if (res.code == 200) {
setFileId(res.data.fileIdList)
message.success("文件上传成功")
setLoadingButton(false)
} else {
message.error(res.msg)
}
})
};
解析部分
multiple多选文件
return false控制只执行一次
customRequest
formdata转文件格式
let formData = new FormData();
uploadFiles.forEach((file: any, index: any) => {
formData.append(`file`, file
);
核心 hook写法
const updateFiles = (function () {
let fileList: any = null;
return function (list: any, setState: any) {
if (!fileList) {
fileList = list;
setState && setState(list);
}
return {
fileList,
reset() {
fileList = false;
}
};
};
})();
总结
我是歌谣 感谢生命中帮助你的每一个人 感谢山川~
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.e1idc.net