React Native的缓存和下载
一般我们有3种数据需要缓存和下载:纯文本(比如API返回,状态标记等),图片缓存和其他静态文件。 纯文本纯文本还是比较简单的,RN官方模块 _storeData = async () => { try { await AsyncStorage.setItem(‘@MySuperStore:key‘,‘I like to save it.‘); } catch (error) { // Error saving data } }; 获取数据 _retrieveData = async () => { try { const value = await AsyncStorage.getItem(‘TASKS‘); if (value !== null) { // We have data!! console.log(value); } } catch (error) { // Error retrieving data } }; 在iOS上,
图片如果一个图片我们已经加载过一次了,下次再用的时候我就不想再加载一次了,最好是直接能从缓存读出来。官方组件 react-native-cached-image你可以跟着官方指引来安装,我就不多说了。但是要注意一点,这个库依赖 react-native-fetch-blob。这是一个native模块,在执行 import React from ‘react‘; import { CachedImage,ImageCacheProvider } from ‘react-native-cached-image‘; const images = [ ‘https://example.com/images/1.jpg‘,‘https://example.com/images/2.jpg‘,‘https://example.com/images/3.jpg‘,// ... ]; export default class Example extends React.Component { render() { return ( <ImageCacheProvider urlsToPreload={images} onPreloadComplete={() => console.log(‘hey there‘)}> <CachedImage source={{uri: images[0]}}/> <CachedImage source={{uri: images[1]}}/> <CachedImage source={{uri: images[2]}}/> </ImageCacheProvider> ); } }
react-native-fast-image
import FastImage from ‘react-native-fast-image‘ const YourImage = () => <FastImage style={styles.image} source={{ uri: ‘https://unsplash.it/400/400?image=1‘,headers:{ Authorization: ‘someAuthToken‘ },priority: FastImage.priority.normal,cache: FastImage.cacheControl.web }} resizeMode={FastImage.resizeMode.contain} /> 它预设了三种模式来控制缓存,其中一个是 其他静态文件有时候我们需要下载或者缓存一些静态文件到设备上,比如pdf,mp3,mp4等。 RNFetchBlob .config({ // add this option that makes response data to be stored as a file,// this is much more performant. fileCache : true,appendExt : ‘zip‘ }) .fetch(‘GET‘,‘http://www.example.com/file/example.zip‘,{ Authorization : ‘Bearer access-token...‘,//some headers .. }) .then((res) => { // the temp file path console.log(‘The file saved to ‘,res.path()) }) 拿到这个路径可以直接用 imageView = <Image source={{ uri : Platform.OS === ‘android‘ ? ‘file://‘ + res.path() : ‘‘ + res.path() }}/> 这个库还可以支持文件上传 RNFetchBlob.fetch(‘POST‘,‘https://content.dropboxapi.com/2/files/upload‘,{ // dropbox upload headers Authorization : "Bearer access-token...",‘Dropbox-API-Arg‘: JSON.stringify({ path : ‘/img-from-react-native.png‘,mode : ‘add‘,autorename : true,mute : false }),‘Content-Type‘ : ‘application/octet-stream‘,// Change BASE64 encoded data to a file path with prefix `RNFetchBlob-file://`. // Or simply wrap the file path with RNFetchBlob.wrap(). },RNFetchBlob.wrap(PATH_TO_THE_FILE)) .then((res) => { console.log(res.text()) }) .catch((err) => { // error handling .. }) 在下载和上传过程中,还可以拿到他的进度: RNFetchBlob.fetch(‘POST‘,‘http://www.example.com/upload‘,{ //... some headers,‘Content-Type‘ : ‘octet-stream‘ },base64DataString) // listen to upload progress event .uploadProgress((written,total) => { console.log(‘uploaded‘,written / total) }) .then((resp) => { // ... }) .catch((err) => { // ... }) RNFetchBlob .config({ // add this option that makes response data to be stored as a file,//some headers .. }) // listen to download progress event .progress((received,total) => { console.log(‘progress‘,received / total) }) .then((res) => { // the temp file path console.log(‘The file saved to ‘,res.path()) }) 要注意点的是, RNFetchBlob .config({ fileCache: true,appendExt: ‘pdf‘,}) .fetch(‘GET‘,‘http://pdf.dfcfw.com/pdf/H3_AP201901271289150621_1.pdf‘) .then((response) => { const path = response.path(); this.setState({ cachedFile: path,}); AsyncStorage.setItem(‘fileCache‘,path); }) .catch((error) => { this.setState({ error,}); }); 检查是不是已经下过这个文件了: componentDidMount() { AsyncStorage.getItem(‘fileCache‘).then((data) => { this.setState({ cachedFile: data,}); }); } 用完了也可以删除这个文件,同时删除记录 clearCache() { const { cachedFile } = this.state; RNFetchBlob.fs.unlink(cachedFile).then(() => { this.setState({ cachedFile: null,}); AsyncStorage. removeItem(‘fileCache‘); }); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |