React Native - 图像缓存

时间:2016-12-06 05:46:21

标签: react-native

我在本网站上阅读了有关React Native图像组件的文档并得到了一些问题:https://facebook.github.io/react-native/docs/image.html

  1. 如果我使用source属性来显示图像。下载后图像是否会被缓存并保存到磁盘?

  2. 如果是,缓存政策是什么?

  3. 如果我想将下载的图像保存到磁盘。使用getSize或prefetch方法更好吗?

  4. 非常感谢。

4 个答案:

答案 0 :(得分:4)

按照here所述,修改本机映像组件NSURLRequest的缓存策略。我个人使用RNFetchBlob缓存图像here。您也可以结帐this component

答案 1 :(得分:2)

您可能对我的高阶组件模块感兴趣,该模块将与性能相关的图像缓存和“永久缓存”功能添加到本机< Image>成分

React Native Image Cache HOC

Tl; DR代码示例:

import imageCacheHoc from 'react-native-image-cache-hoc';
const CacheableImage = imageCacheHoc(Image);

export default class App extends Component<{}> {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <CacheableImage style={styles.image} source={{uri: 'https://i.redd.it/rc29s4bz61uz.png'}} />
        <CacheableImage style={styles.image} source={{uri: 'https://i.redd.it/hhhim0kc5swz.jpg'}} permanent={true} />
      </View>
  );
  }
}

第一个图像将被缓存,直到总局部缓存增长超过15 MB(默认情况下),然后缓存的图像将被删除最早,直到总缓存再次低于15 MB。

第二张图像将永久存储到本地磁盘。人们使用此功能替代您的应用程序运送静态图像文件。

这应该开箱即用。希望它有所帮助!

答案 2 :(得分:1)

FastImage最适合图像缓存

添加纱线react-native-fast-image

参考:https://github.com/DylanVann/react-native-fast-image

其最大道具的行为类似于React native image属性

import FastImage from 'react-native-fast-image'


<FastImage
    style={{ width: 200, height: 200 }}
    source={{ uri: 'https://unsplash.it/400/400?image=1' }}
    resizeMode={FastImage.resizeMode.stretch}

/>

答案 3 :(得分:1)

过程

React Native 在下载和解码图像后会缓存图像。 enter image description here

缓存策略

  1. 到期时间

2.使用位图大小作为缓存开销;默认情况下,React Native iOS 中总共 20MB 缓存容量

  1. iOS 中 NSCache 中的未知存储和驱逐政策

How Image Loader and Cache work in React Native under the hood中查看更多