我有 7 个 URL,其中有时 3-4 个是有效的可下载图像。所以在使用 getPhotosList 函数渲染图像之前,我使用函数CheckValidImages检查有效下载 URL
const CheckValidImages = async () => {
if (!props.location.state.isVideoContent) {
let getRecipeDetailWorkflowRead = {props.location.state.recipeDetailWorkflowRead};
let recipePhotos = [];
let sequence = 0;
for (var i = 0; i < getRecipeDetailWorkflowRead.recipePhotos.length; i++) {
const img = new Image();
img.src = getRecipeDetailWorkflowRead.recipePhotos[i].path;
await img
.decode()
.then(() => {
getRecipeDetailWorkflowRead.recipePhotos[i].sequence = sequence + 1;
recipePhotos.push(getRecipeDetailWorkflowRead.recipePhotos[i]);
sequence = sequence + 1;
})
.catch((encodingError) => {});
}
getRecipeDetailWorkflowRead.recipePhotos = recipePhotos;
setRecipeDetailWorkflowRead(getRecipeDetailWorkflowRead);
setImageLoader(false);
} else {
setRecipeDetailWorkflowRead(
props.location.state.recipeDetailWorkflowRead
);
}
};
const getPhotosList = () => {
if (recipeDetailWorkflowRead.recipePhotos !== undefined) {
console.log(recipeDetailWorkflowRead.recipePhotos);
var listItems = recipeDetailWorkflowRead.recipePhotos.map((el, i) => {
return (
<div
key={i}
className={['mr-1', Classes.imagediv].join(' ')}
draggable='true'
onDragEnd={dragEnd}
onDragStart={dragStart}
data-item={JSON.stringify(el)}
>
<img
className={i === 0 ? Classes.card_img_first : Classes.card_img}
src={el.path}
alt='cardimg'
/>
<div className={Classes.card_body}>
<input
type='text'
name='mediaDescription'
value={el.mediaDescription || ''}
onChange={(event) => onAltTextChangehandler(event, i)}
placeholder='Alt text'
className={['form-control', Classes.img_alt_text].join(' ')}
/>
</div>
</div>
);
});
return (
<div
onDragOver={dragOver}
className={['d-flex', 'flex-row', Classes.contain].join(' ')}
>
{listItems}
</div>
);
}
};
在 CheckValidImage 函数中,getRecipeDetailWorkflowRead.recipePhotos[i].path有一个图像路径,我检查它是否有效。现在,如果图像有效,我尝试将其推送到 recipePhotos 中,最后在检查完所有图像路径后,我更新状态 setRecipeDetailWorkflowRead
但是,如果图像尺寸较大,这似乎很耗时。有人可以建议我可以更快地检索图像的其他替代选项。