如何刷新外部更改的图像?

时间:2019-02-28 18:54:10

标签: javascript reactjs webpack webpack-file-loader

这基本上是我要尝试的事情:

  • 单击按钮,请求服务器截屏

    adb exec-out screencap -p > $(pwd)/src/assets/screenshots/screen.png

    所以我将结果保存在/src中,并且确保操作完成后返回了响应,以防止在保存图像时采取措施。

  • 从服务器获得响应(意味着图像已更改)后,除了要刷新的图像外,我。

因此,每次我单击按钮时,我都希望图像发生变化。但是到目前为止,无论我做什么,它始终仅显示初始图片


项目结构:

project

├── build
├── node_modules
├── server
│     ├── services
│     └── app.py
├── src
...   ├── assets
      │     ├── screenshots
      │    ...       └── screen.png
      ├── config
      ├── helpers
      ├── modules
      ├── index.html
      ├── index.js
     ...

反应功能(实验不同情况):

import React, { useState } from "react";
import { api } from "../helpers/api";
import * as config from "../config/client";
import IMG from "../assets/screenshots/screen.png";

const SS_ENDPOINT = config.endpoint + "screenshot";

function Home() {
  const [time, setTime] = useState(new Date().getTime());

  const ss = () => {
    api
      .get(SS_ENDPOINT)
      .then(ignored => {
        setTime(new Date().getTime());
      })
      .catch(e => console.log(e));
  };

  let images = require.context("../assets/screenshots/", true);
  let image = images("./screen.png");

  console.log(image);
  console.log(IMG);

  return (
    <div className="home">
      <img src={`${image}?${time}`} height={200} width={50} />
      <img src={`../assets/screenshots/screen.png?${time}`} height={200} width={50} />
      <img src={`/src/assets/screenshots/screen.png?${time}`} height={200} width={50} />
      <img src={`src/assets/screenshots/screen.png?${time}`} height={200} width={50} />
      <img src={IMG} height={200} width={50} />
      <img src={`${IMG}?${time}`} height={200} width={50} />
      <button onClick={ss}>SS</button>
    </div>
  );
}

export default Home;

结果

按钮单击没有变化,但是我可以看到每次单击都会获取图像,但它仍然是初始图像。

resulting images, here blacks are initial images


我不确定这种方法是否正确或是否有更好的方法。如果我采用的方法不正确,请纠正我。

TL; DR:如何在反应中显示外部更改的图像?我尝试通过require()或直接链接来引用图像,但它似乎总是从/build获取初始图像,并且从未更改

0 个答案:

没有答案