代码之家  ›  专栏  ›  技术社区  ›  Attila

如何强制图像刷新

  •  1
  • Attila  · 技术社区  · 7 年前

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

    我有好几个部门都有 backgroundImage 财产。我点击的网址是: https://source.unsplash.com/collection/1163637/480x480

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

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

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

    2 回复  |  直到 7 年前
        1
  •  6
  •   Michael    7 年前

    您可以向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);
    }
    
        2
  •  3
  •   Countingstuff    7 年前

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

    它现在起作用了。(请注意,url更改其提供的图像大约需要5秒钟)

    推荐文章