如何从 URL 下载图像并缓存 Android (React-Native)

How to download images from URL and cache the for Android (React-Native)

我需要从url下载一张图片并将其缓存到应用程序的缓存目录中。我正在 react-native 平台上开发应用程序。据我所知,我在 IOS 工作的队友有一个允许缓存图像的道具,但 Android 尚不支持此道具。我需要一种缓存 Android 图像的好方法。

react-native 版本:0.60.5

我试过使用 rn-fetch-blob 库。我设法将图像存储在缓存中,但是,当我使用路径

RNFetchBlob
  .config({
    fileCache : true,
    appendExt : 'jpg'
  })
  .fetch('GET', 'some url from firebase storage', {
  })
  .then((res) => {
     this.setState({ imagePAth: res.path() })
  })
<Image
  style={{ width: 200, height: 200, resizeMode: "contain" }}
  source={{ uri: "file://" + this.state.imagePath }}
/>

它不渲染图像。

我的其他队友说 react-native-fs 库坏了,不能用。所以我信任他们,但如果有人设法用 react-native-fs 做到这一点,请告诉我。

我也尝试过使用 react-native-cached-image,但它总是给我错误

undefined is not an object Netinfo.isconnected

最新版本的 react-native-cached-image 需要 react-native-community 的 netinfo 库。顺便说一句,我已连接到互联网。我正在使用库中的代码示例对其进行测试。

如果你需要引用我使用的库:https://github.com/fungilation/react-native-cached-image

如果有任何帮助,我将不胜感激。谢谢!

你可以试试react-native-fast-image

yarn add react-native-fast-image or npm install --save react-native-fast-image

Note: You must be using React Native 0.60.0 or higher to use the most recent version of react-native-fast-image.

例子

import FastImage from 'react-native-fast-image'

const YourImage = () => (
    <FastImage
        style={{ width: 200, height: 200 }}
        source={{
            uri: 'https://unsplash.it/400/400?image=1',
            headers: { Authorization: 'someAuthToken' },
            priority: FastImage.priority.normal,
        }}
        resizeMode={FastImage.resizeMode.contain}
    />
)

感谢您的回复。我找到了另一个可以在 IOS 和 Android 上找到的库。 react-native-image-cache-hoc。至少它在 react-native: 0.60.5 上运行良好。我没有尝试react-native-fast-image,但如果人们说它有效,那么它应该是。

请参考:https://github.com/billmalarky/react-native-image-cache-hoc 如果你对图书馆感兴趣。