require.context不会随着图像上传而更新

时间:2019-09-11 08:07:07

标签: javascript node.js webpack react-router

当我在upload.js中上传新图像并返回gallery.js时,require.context不会随着新图像导入而更新。我在目录中看到该文件,因此正在上传。

我尝试过强制重新渲染,但是没有任何变化。我不确定这是否与react-router有关,还是必须异步进行。

//Gallery.js
  componentDidMount() {
    const interval = setInterval(this.importAll, 3000);
    this.setState({interval});
  }

  componentWillUnmount() {
    clearInterval(this.state.interval);
  }

  importAll() {
    const images = [];

    //requires all the images from the uploads directory
    let context = require.context('../../uploads', false, /\.(png|jpe?g|PNG|JPE?G)$/);

    context.keys().forEach(item => { 
                        images.push(context(item)); 
                    });

    this.setState({images});
  }

...

//Upload.js
    axios.post('http://localhost:3000/upload', data)
          .then (res => {
             console.log(res);
             this.props.history.push("/"); 
            })
          .catch((error) => {
            console.log(error);
          });
  }

...

1 个答案:

答案 0 :(得分:0)

我将假设上下文实际上是由webpack缓存的,这就是为什么即使重新渲染也看不到它的更新的原因,因此您需要刷新页面才能看到更改。

这当然在生产上可能有所不同。

我要做的是有一个addSingleImage方法

pgrep

,然后在成功的帖子中调用该链接,并附带您成功上传的图片的路径。