首页 > 解决方案 > 如何强制刷新图像

问题描述

这是我正在处理的一个小项目:https ://codesandbox.io/embed/rwxookx6po 。

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

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

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

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

标签: reactjsbackground-image

解决方案


您可以在 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);
}

推荐阅读