如何在React中缓存图像? [英] How To Cache Images in React?

查看:614
本文介绍了如何在React中缓存图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个网址列表如下:

Suppose I have a list of url's like so :

['/ images / 1','/ images / 2',. ..]

我想预取 n 那些之间的过渡图像更快。我现在在 componentWillMount 中做的是以下内容:

And I want to prefetch n of those so that transitioning between images is faster. What I am doing now in componentWillMount is the following:

componentWillMount() {
      const { props } = this;
      const { prefetchLimit = 1, document = dummyDocument, imgNodes } = props;
      const { images } = document;
      const toPrefecth = take(prefetchLimit, images);
      const merged = zip(toPrefecth, imgNodes);

      merged.forEach(([url, node]) => {
        node.src = url;
      });
    }

imgNodes 正在定义如下:

imgNodes:times(_ => new window.Image(),props.prefetchLimit),

zip 和<来自 ramda 的code> 。

and times, zip, and take coming from ramda.

现在当我在里面使用这些网址时反应如下:

Now when I use those urls inside of react like so:

< img src = {url} />

它根据 Etag 点击浏览器缓存无论网址在何处使用,都会过期标记。每当我们在视图内点击 n - 1 时,我还计划使用它来预取下一个 n 图像,重复使用 imgNodes 以同样的方式。

it hits the browser cache according to the Etag and Expire tags regardless of where the url is used. I also plan on using this to prefetch the next n images whenever we hit n - 1 inside of the view, reusing imgNodes in the same manner.

我的问题是:


  • 这是否是一个有效的想法,会给出100多个使用这个想法的组件,但一次只能看到1个?

  • Is this even a valid idea give 100+ components that will use this idea but only 1 will be visible at a time?

这样做会遇到内存问题吗?我假设卸载组件时将收集 imgNodes 进行垃圾回收。

Will I run into memory issues by doing this? I am assuming that imgNodes will be garbage collected when the component is unmounted.

我们正在使用 redux 所以我可以保存这些图像在商店,但似乎我正在处理缓存而不是利用浏览器的自然缓存。

We are using redux so I could save these images in the store but that seems like I am handling the caching instead of leveraging the browser's natural cache.

这个想法有多糟糕?

推荐答案

您无需在所有组件中执行此操作。一旦下载了图像,它就会被浏览器缓存,并且可以在所有组件中访问,因此您只能在高级组件中的某个位置执行此操作。

You don't need to do it in all of your components. As soon as an image is downloaded it gets cached by the browser and will be accessible in all components, so you can do this only once somewhere in a high-level component.

我不知道您试图通过缓存图像创建的UX究竟是什么,但是,您的代码仅启动下载图像,但不知道图像是否正在下载,是否已成功下载甚至失败。因此,例如,您想要显示一个按钮来更改图像或仅在下载图像时将类添加到组件(为了使其顺利),您当前的代码可能会让您失望。

I don't know what exactly UX you are trying to create by caching images, however, your code only initiates downloading images but doesn't know whether an image is being downloaded, has been downloaded successfully or even failed. So, for example, you want to show a button to change images or add a class to a component only when the images have been downloaded (to make it smooth), your current code may let you down.

您可能希望使用Promises解决此问题。

You may want to resolve this with Promises.

// create an utility function somewhere
const checkImage = path =>
    new Promise(resolve => {
        const img = new Image()
        img.onload = () => resolve(path)
        img.onerror = () => reject()

        img.src = path
    })

...

// then in your component
class YourComponent extends Component {

    this.state = { imagesLoaded: false }

    componentDidMount = () =>
        Promise.all(
            R.take(limit, imgUrls).map(checkImage)
        ).then(() => this.setState(() => ({ imagesLoaded: true })),
               () => console.error('could not load images'))

    render = () =>
        this.state.imagesLoaded
            ? <BeautifulComponent />
            : <Skeleton />
}

关于内存消耗 - 我认为不会发生任何不好的事情。浏览器通常会限制并行xhr请求的数量,因此您将无法创建巨大的堆使用峰值来崩溃任何内容,因为未使用的图像将被垃圾收集(但仍保留在浏览器缓存中)。

Regarding memory consumption — I don't think anything bad will happen. Browsers normally limit the number of parallel xhr requests, so you won't be able to create a gigantic heap usage spike to crash anything, as unused images will garbage collected (yet, preserved in browser cache).

Redux商店是存储应用程序状态的地方,而不是应用程序资产,但无论如何,您将无法在那里存储任何实际图像。

Redux store is a place to store the app state, not the app assets, but anyway you won't be able to store any actual images there.

这篇关于如何在React中缓存图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆