【发布时间】:2017-03-08 13:12:19
【问题描述】:
是否有一个好的库或者一些默认的反应原生组件来缓存来自 url 的图像? 我试过react-native-cache-image,但react-native-fs 和react-native-sqlite-storage 有很多问题,而且我是新手,不知道如何正确修复它们。
【问题讨论】:
-
您是否尝试存储缓存图像?
标签: android ios caching react-native
是否有一个好的库或者一些默认的反应原生组件来缓存来自 url 的图像? 我试过react-native-cache-image,但react-native-fs 和react-native-sqlite-storage 有很多问题,而且我是新手,不知道如何正确修复它们。
【问题讨论】:
标签: android ios caching react-native
yarn add react-native-fast-image
参考:https://github.com/DylanVann/react-native-fast-image
import FastImage from 'react-native-fast-image'
<FastImage
style={{ width: 200, height: 200 }}
source={{ uri: 'https://unsplash.it/400/400?image=1' }}
resizeMode={FastImage.resizeMode.stretch}
/>
【讨论】:
您可能对我的高阶组件模块感兴趣,它为原生
Tl;DR 代码示例:
import imageCacheHoc from 'react-native-image-cache-hoc';
const CacheableImage = imageCacheHoc(Image);
export default class App extends Component<{}> {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<CacheableImage style={styles.image} source={{uri: 'https://i.redd.it/rc29s4bz61uz.png'}} />
<CacheableImage style={styles.image} source={{uri: 'https://i.redd.it/hhhim0kc5swz.jpg'}} permanent={true} />
</View>
);
}
}
将缓存第一个图像,直到总本地缓存增长超过 15 MB(默认情况下),然后首先删除最旧的缓存图像,直到总缓存再次低于 15 MB。
第二个图像将永久存储到本地磁盘。人们将其用作与您的应用一起运送静态图像文件的替代品。
听起来您也有兴趣将图像文件任意存储到本地磁盘。您可以使用 CacheableImage 静态方法来做到这一点,如下所示:
import imageCacheHoc from 'react-native-image-cache-hoc';
const CacheableImage = imageCacheHoc(Image);
CacheableImage.cacheFile('https://i.redd.it/hhhim0kc5swz.jpg', true)
.then( localFileInfo => {
console.log(localFileInfo);
// Console log outputs:
//{
// url: 'https://i.redd.it/rc29s4bz61uz.png',
// cacheType: 'permanent',
// localFilePath: '/this/is/absolute/path/to/file.jpg'
//}
});
希望这会有所帮助!
【讨论】:
我已经使用过这个库,并且在 android 和 ios 手机上都可以使用。它适用于 EXPO 和 ReactNative。在 react native 中自动存储捕获图像。
安装库:
纱线添加 picache
然后像这样在你的js文件中使用,首先导入文件并使用它。欲了解更多信息click
import Picache from "picache";
const App = () => (
<Picache
style={{ height: 150, width: 350 }}
source={require("./square.png")}
/>
);
【讨论】:
直接来自 Expo 文档:
import React from 'react';
import Expo from 'expo';
import { Image, View } from 'react-native';
import logo from './assets/icon.png';
const cacheImages = images => images.map(image => {
if (typeof image === 'string') return Image.prefetch(image);
return Expo.Asset.fromModule(image).downloadAsync();
});
class View extends React.component {
state = {
appIsReady: false
}
componentWillMount() {
this.loadAssetsAsync();
}
async loadAssetsAsync = () => {
const imageAssets = cacheImages([icon]);
await Promise.all([...imageAssets]);
this.setState({ appIsReady: true });
}
render() {
return(
<View>
<Image source={logo} style={styles.imageStyle} />
</View>
);
}
}
我认为代码 sn-p 是直截了当的。加载所有图像后,您的状态将设置为true。您将拥有为您处理工作的cacheImages 函数。您需要的唯一要求是Expo。
【讨论】:
Image 组件中内置了prefetch() 方法。
【讨论】: