0

我有 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

但是,如果图像尺寸较大,这似乎很耗时。有人可以建议我可以更快地检索图像的其他替代选项。

4

1 回答 1

0

我不知道反应,但我认为你可以做一个'HEAD'请求并检查标题而不下载内容:

var url = 'https://nystudio107-ems2qegf7x6qiqq.netdna-ssl.com/img/blog/_1200x630_crop_center-center_82_none/craft-cms-custom-field-leveraging-platform-2.jpg?mtime=1598495914';
var p = fetch(url, { method: 'HEAD' });
p.then(r => {
  if (r.status === 200 && r.headers.get('content-type') === 'image/jpeg')
  {
    console.log('Found an image!  Size is:', r.headers.get('content-length'));
  }
});

于 2020-12-14T18:45:53.927 回答