1 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超13個(gè)贊
確定找到了解決方案,所以我會(huì)分享它。將整個(gè)列表發(fā)送到 util 函數(shù)并在那里進(jìn)行處理。在 util func 中,我將更新一個(gè)狀態(tài),該狀態(tài)將是可選的加載文件。只有在檢查之后,我才會(huì)在組件內(nèi)部設(shè)置“真實(shí)”圖像列表——這將在 util 之外發(fā)生:
useEffect(()=>{
uploaded.map((obj, index) => {
if (isValid) {
setImagesList((old) => [...old, obj]);
}
},[uploaded])
-----------------------------------
util :
export default function loadFiles(files, setUploaded) {
const reader = new FileReader();
let arr = [];
function readFile(index) {
if (index >= files.length || index > 5) {
setUploaded(arr);
return;
}
const file = files[index];
reader.onload = function (e) {
let image = new Image();
image.src = e.target.result;
image.onload = function () {
arr.push({
key: `${Date.now()}-${file.name}-${index}`,
name: file.name,
arr: [e.target.result],
imageOriginalWidth: image?.width,
imageOriginalHeight: image?.height,
});
readFile(index + 1);
};
};
reader.readAsDataURL(file);
}
readFile(0);
}
添加回答
舉報(bào)