managed wifi
即使您使用的是Expo的托管工作流程,在React Native中缓存图像也很容易。 许多开发人员遇到的问题是,React Native仅支持开箱即用地在IOS上缓存图像 。
在Android上运行的其他流行社区软件包均包含本机代码,因此不适用于Expo的托管工作流程 。 因此,我将最新项目中使用的代码开源。 看, react-native-expo-cached-image !
快速开始
安装模块:
yarn add react-native-expo-cached-image
导入组件:
import CachedImage from 'react-native-expo-cached-image' ;
在render()方法中使用组件:
<CachedImage
isBackground
source={{ uri:'https://qvault.io/wp-content/uploads/2019/05/QVault-app.png' }}
/>
CachedImage组件与React Native的Image和ImageBackground组件具有相同的道具和API。 要将CachedImage用作背景图像,只需传递isBackground属性即可 :
<CachedImage
isBackground
source={{ uri:'https://qvault.io/wp-content/uploads/2019/05/QVault-app.png' }}
/>
它在做什么?
CachedImage使它保持简单。 它将使用URI的SHA-256哈希将映像下载到用户的本地文件系统。 然后,在后续渲染和应用程序使用时,它将从文件系统中加载图像(如果存在)。 这样可以避免用户使用不必要的数据,并避免加载时间过长。
提示:为了破坏缓存,您可以在URI后面附加查询字符串或锚文本。
码
在编写本文时,以下是代码,如果您不想安装依赖项,请随意复制它:
import React, { Component } from 'react' ;
import { View, Image, ImageBackground } from 'react-native' ;
import * as FileSystem from 'expo-file-system' ;
import * as Crypto from 'expo-crypto' ;
export default class CachedImage extends Component {
state = {
imgURI: ''
}
async componentDidMount() {
const filesystemURI = await this .getImageFilesystemKey( this .props.source.uri);
await this .loadImage(filesystemURI, this .props.source.uri);
}
async componentDidUpdate() {
const filesystemURI = await this .getImageFilesystemKey( this .props.source.uri);
if ( this .props.source.uri === this .state.imgURI ||
filesystemURI === this .state.imgURI) {
return null ;
}
await this .loadImage(filesystemURI, this .props.source.uri);
}
async getImageFilesystemKey(remoteURI) {
const hashed = await Crypto.digestStringAsync(
Crypto.CryptoDigestAlgorithm.SHA256,
remoteURI
);
return `${FileSystem.cacheDirectory}${hashed}`;
}
async loadImage(filesystemURI, remoteURI) {
try {
// Use the cached image if it exists
const metadata = await FileSystem.getInfoAsync(filesystemURI);
if (metadata.exists) {
this .setState({
imgURI: filesystemURI
});
return ;
}
// otherwise download to cache
const imageObject = await FileSystem.downloadAsync(
remoteURI,
filesystemURI
);
this .setState({
imgURI: imageObject.uri
});
}
catch (err) {
console.log( 'Image loading error:' , err);
this .setState({ imgURI: remoteURI });
}
}
render() {
return (
<View>
{ this .props.isBackground ? (
<ImageBackground
{... this .props}
source={ this .state.imgURI ? { uri: this .state.imgURI } : null }
>
{ this .props.children}
</ImageBackground>
) : (
<Image
{... this .props}
source={ this .state.imgURI ? { uri: this .state.imgURI } : null }
/>
)}
</View>
);
}
}
谢谢阅读
翻译自: https://hackernoon.com/how-to-cache-images-in-an-expo-managed-react-native-app-5q9m3z6s
managed wifi