React Native清除缓存实现

清除缓存使用的第三方:react-native-http-cache
 
Github: https://github.com/reactnativecn/react-native-http-cache
 
社区讨论: http://bbs.reactnative.cn/topic/150/%E7%BC%93%E5%AD%98%E7%AE%A1%E7%90%86/9
 
界面实现如下:
 
1.导入框架: 
$ npm install react-native-http-cache --save

2.确保库添加上,没有添加自己添加下:

3.报错如下,解决方式:

一看就晓得这个是重复导入引起的。注释重复导入的组件即可。

 

4.具体清除缓存代码:

import * as CacheManager from 'react-native-http-cache'

//
获得缓存大小 async getCacheSize() { const data = await CacheManager.getCacheSize(); const size = data / (1024 * 1024); this.setState({ cacheSize: size.toFixed(2) + 'M'}); } // 清除缓存 async clearCacheSize() { await CacheManager.clearCache(); // this.getCacheSize(); // 这里貌似清除不能全部清除为0,这里直接写死0即可。 this.setState({cacheSize: '0M'}); alert('清除缓存成功'); }

这里直接使用state存储cacheSize即可。最后有些会没有清除,这里直接写死即可,反正缓存不大😄😄

注意:直接使用Github上提供的方法报错。使用上面即可。

 // 注意: 这里依照官方Demo报错,修改如下方法即可。
    // async getData(){
    //     try {
    //       this.setState({
    //         'http': await httpCache.getHttpCacheSize(),
    //         'image': await httpCache.getImageCacheSize(),
    //         'all': await httpCache.getSize(),
    //       });
    //     } catch(err){
    //       alert('错误', err.message);
    //     }
    //   }
    // async clearCache(){
    //     try {
    //       await httpCache.clear();
    //       alert('清除缓存成功');
    //       await this.getData();
    //     } catch(err){
    //       alert('错误', err.message);
    //       console.log('----'+ err.message + '-----'); // httpCache.clear is not a function
    //     }
    //   }

 

 

posted on 2017-11-09 17:17  玉思盈蝶  阅读(10519)  评论(1编辑  收藏  举报

导航