如何缓存/保存图像以进行反应并显示它们?

时间:2018-04-25 07:42:49

标签: javascript reactjs redux html5-canvas react-redux

我有一个图片网址列表。这些图像中的每一个有时会加载,有时会加载404(意味着某个点加载的图像可能会在以后消失)。

let images = ['http://example.com/img1.jpg', ...];

有没有办法请求这些图像,如果请求成功则将它们保存在内存中,并在React中显示这些保存的图像?

componentDidMount() {
  this.setState({ savedImages: images.map(saveImage)} );
}

render() {
  return (
    <div><image src={this.state.savedImages[0]}/></div>
  );
}

1 个答案:

答案 0 :(得分:2)

好的,让我代表评论中的全部信息作为完整答案。

备注:问题实际上不是特定于React,而是vanilla JS。

想法是动态创建Image实例:

/* Somewhere inside the React class, I think */

preloadImages = () => {
    let links = ["link1", "link2", "link3"]

    /* the one react-specific thing is this.setState */
    this.setState({ images: links.map((link, i) => {
        // create an Image instance
        var img = new Image()
        // setting handler for load complete
        img.onload = () => this.handleImageLoad(i)
        // set the src attribute for it. After this line image loading will start
        img.src = link
        // return object with indicate of image loading statement
        return {
            url: link,
            loaded: false
        }
    }) })
}

// nuff said, I suppose, this function is clear :)
handleImageLoad = index => {
    var { images } = this.state
    images[i].loaded = true
    this.setState({ images })
}

显然,现在你可以在渲染中使用this.state.images并仅渲染已经加载的图像:)