React Native圖片快取元件
今天介紹一個React Native的圖片快取元件ofollow,noindex">react-native-rn-cacheimage ,純JS實現,所以相容性很好。
大家都知道,其實React Native 的Image
元件在iOS
端實現了快取,而android
端仍未實現,而且,就算實現了iOS
端 ,可能有些需求仍然比較難實現,比如一般APP都有一個清除快取
的功能,如果我們使用預設的Image
的快取實現,我們能難定點陣圖片到底快取在本地檔案系統的哪個目錄。react-native-rn-cacheimage
的實現方式是,把所有的快取圖片都放在一個指定的資料夾下,並提供了一個方法CacheHelper.clearCache()
方法能夠輕鬆清除快取。
下面我們就來介紹下它的安裝及使用
安裝
rn-fetch-blob
react-native-rn-cacheimage
使用到了rn-fetch-blob
這個package,由於rn-fetch-blob
的實現涉及到了native
程式碼,所以安裝會比較複雜,強烈建議按照官方安裝手冊
來安裝。當然,一般情況下使用以下兩個命令來安裝就可以:
$ npm install rn-fetch-blob --save $ react-native link rn-fetch-blob 複製程式碼
如果有問題,建議按照官方安裝手冊
的手動link
的方式來安裝。
react-native-rn-cacheimage
由於這個package本身是純js
來實現的,沒有涉及iOS
和android
的原生代碼,所以安裝很簡單:
$ npm install react-native-cacheimage --save 複製程式碼
使用
Register和unregister
-
在使用
CacheImage
和AnimatedCacheImage
之前,需要初始化相關資訊,建議在APP嘴頂層的component
的componentDidMount()
中初始化 -
在APP的頂層
component
的componentWillUnmount()
中,執行清除任務
具體操作,見如下程式碼 :
import React from 'react' import {AppRegistry} from 'react-native' import {Provider} from 'react-redux' import ReduxStore from './src/configuration/reduxStore' import App from './src/App' import {CacheHelper} from "react-native-rn-cacheimage"; const store = ReduxStore class MyApp extends React.Component { componentDidMount() { CacheHelper.register({overwrite:false}).catch(e => console.log(e)) } componentWillUnmount() { CacheHelper.unregister().catch(e=>console.log(e)) } render() { return ( <Provider store={store}> <App/> </Provider> ) } } AppRegistry.registerComponent("YourAppName", () => MyApp); 複製程式碼
使用CacheImage和AnimatedCacheImage元件
CacheImage元件
CacheImage
元件可以代替原有的Image
及ImageBackground
元件使用,並且props
與Image
及ImageBackground
引數保持一致.
import {CacheImage} from 'react-native-rn-cacheimage' export default class Example extends React.Component { ... render() { return ( <View> <CacheImage source={{uri:'https://xxx.xxx'}} defaultSource={require('/xxx/xxx.png')} style={styles.image} /> <CacheImage source={{uri:'https://xxx.xxx'}} defaultSource={require('/xxx/xxx.png')} style={styles.image} > <Text>Hello World!</Text> </CacheImage> </View> ) } ... } 複製程式碼
AnimatedCacheImage元件
AnimatedCacheImage
可以 代替Animated.Image
元件,並且所有引數與Animated.Image
保持一致
import {AnimatedCacheImage} from 'react-native-rn-cacheimage' export default class Example extends React.Component { ... render() { return ( <View> <AnimatedCacheImage source={{uri:'https://xxx.xxx.png'}} defaultSource={require('/xxx/xxx.png')} style={styles.image} /> </View> ) } ... } 複製程式碼
CacheHelper的API
CacheHelper
是一個輔助類,裡面包含一些工具方法,大家可以根據自己的需求,選擇呼叫。這裡就不全部列出來,大家可以直接到Github
上檢視
getCacheSize():Promise<Number>
獲取所有的快取圖片所佔用記憶體大小,返回的數字結果單位是byte
getCacheSizeFormat():Promise<String>
這個與getCacheSize()
很相似,只不過它的返回結果是已經格式化好的,比如:10.2MB
,98KB
clearCache():Promise<Void>
清空快取。一般我們APP都會有一個清空快取的功能,我們可以呼叫這個方法清空我們使用這個package
所產生的快取檔案。