react native 清除缓存
2019-04-22 本文已影响0人
路遇惊喜
1、安装react-native-http-cache
npm install react-native-http-cache --save
2、Linking Libraries
react-native link react-native-http-cache
执行这个命令之后,Android和iOS项目都会把库链接进去。

(PS: 如果该命令添加失败的话,需要自己在Xcode或者Android Studio 手动添加。)
3、分别配置Android
平台和iOS
平台
我也是按照github的文档配置的。
3.1 Android
把项目里面的android目录拖进Android Studio
3.1.1、修改MainApplication.java
文件

3.1.2、Android 修改 HttpCacheModule.java
文件
(目录为node_modules>react-native-http-cache>android>src>main>java>cn>reactnative>httpcache>HttpCacheModule.java)
//将69改成:
FileCache cache1 = ImagePipelineFactory.getInstance().getMainFileCache();
/将80行改成:
FileCache cache2 = ImagePipelineFactory.getInstance().getSmallImageFileCache();
如果不修改以上2个方法,会显示如下报错:

3.2、iOS
把项目里面的ios目录拖进Xcode

4、在react native 项目使用react-native-http-cache
import * as CacheManager from 'react-native-http-cache';
我把CacheManager
打印了一下,可以看到它有这些方法:

以下方法返回的是一个 promise 对象
方法 | 说明 |
---|---|
CacheManager.clearCache() | 清除缓存 |
CacheManager.clearHttpCache() | 清除网络缓存 |
CacheManager.clearImageCache() | 清除图片缓存 |
CacheManager.getCacheSize() | 返回网络缓存大小和图片缓存大小 |
CacheManager.getImageCacheSize() | 获取图片缓存 |
CacheManager.getHttpCacheSize() | 获取网络缓存 |
//获取缓存
getCache(){
CacheManager.getCacheSize().then(res=>{
let cacheSize = Math.round((res / 1024 / 1024) * 100) / 100 + 'M';
this.setState({
cacheSize
})
},err=>{
console.log(err)
})
}
//清除缓存
clearCache(){
CacheManager.clearCache();
this.setState({
cacheSize: '0M'
})
}
经测试,清楚缓存之后,还是会有0.15M 。为了界面好看点,我在上面的代码中直接设置清除缓存后为0M了。
