首页 > 解决方案 > React 应用程序在多个异步图像下载时重新加载

问题描述

在从 create-react-app 创建的节点中运行一个反应应用程序,我有一个代理节点服务器正在运行,我有一个 API 设置来从 azure blob 存储下载图像。问题是每当我从 react 中连续多次调用 /api/downloadimage 时,页面都会重新加载,就好像 react 放弃了渲染并丢失了应用程序的状态一样。图像确实会下载,但应用程序会刷新。当我只打一次电话时,问题不会发生。

Nodemon 正在运行 server.js。尝试告诉 nodemon 忽略对图像下载到的目录的更改,似乎没有效果。

节点内:

app.get('/api/downloadplateimage', function(req, res, next) {
  const plateName = req.query.name;
  downloadPlate(plateName)
    .then(response => {
        res.json(response);
    }).catch(error => {
        res.json({ success: false });
    });
});

const downloadPlate = (blobName) => {
  return new Promise((resolve, reject) => {
    blobService.getBlobToLocalFile(platesContainer, blobName, imagesDir + '/plates/' + blobName, err => {
        if (err) {
            reject(err);
        } else {
            resolve({ success: true });
        }
    });
  });
};

内反应:

componentDidMount() {
  Promise.all([
    this._downloadImage('<guid>.jpeg'),
    this._downloadImage('<guid>.jpeg')
  ]).then(res => {
    console.log('fetched images');
  });
}

_downloadImage = (imageName) => {
  return fetch(`/api/downloadplateimage?name=${imageName}`)
    .then(r => r.json())
    .then(body => {
      let imageAvailable = false;
      if (body.success) {
        imageAvailable = true;
      }
      ...
      this.setState({imageAvailable});
  });
}

标签: node.jsreactjsasynchronousfetchazure-blob-storage

解决方案


最终放弃了下载 blob 并使用 Azure 之外的 URL 来代替 img src(s)。


推荐阅读