如何强制刷新图像

How to force an image to refresh

这是我正在完成的一个小项目:https://codesandbox.io/embed/rwxookx6po

我有几个具有 backgroundImage 属性 的 div。我打的url是这个:https://source.unsplash.com/collection/1163637/480x480

每次访问 url,您都会从 collection 中获得一张新的随机图像。我以为因为道具没有改变,我可以强制我的组件更新,但这似乎并没有解决问题:

shouldComponentUpdate(nextProps) {
    if (nextProps.image) {
      this.forceUpdate();
      return true;
    }
  }

如果我按下一个按钮并将相同的图像 url 道具传递到我的包含带有背景图像的 div 的组件,我怎样才能让组件重新加载,给我的 div 一个新的图像背景?

这是一个彻头彻尾的破解,但我认为问题在于浏览器正在缓存请求的结果,因此不会通过替换

再次进入 url

const imageURL = `https://source.unsplash.com/collection/1163637/${width}x${height}?random=${Math.random()}`;

现在可以了。 (请注意,url 更改它提供的图像大约需要 5 秒)

您可以向 updateImage 方法添加时间戳,如下所示:

updateImage() {
  const width = 480;
  const height = 480;
  const timestamp = Date.now();
  const imageURL = `https://source.unsplash.com/collection/1163637/${width}x${height}?t=${timestamp}`;
  return this.props.updateImage(imageURL, width, height);
}