我的应用程序不断显示我的旧图像。我没有存储桶版本控制。我尝试重新启动应用程序,但它一直显示这个旧图像。它是否以某种方式进行缓存?有什么解决办法吗?
React-Native 的 Image 组件为 iOS 的 source prop 提供了缓存扩展。您可以尝试将缓存设置为“重新加载”吗?
<Image
source={{
uri: 'https://reactjs.org/logo-og.png',
cache: 'reload'
headers: {Pragma: 'no-cache'} // Android Support
}}
style={{ width: 400, height: 400 }}
/>
注意,仅支持 iOS
从 AWS S3 获取图像时我遇到了类似的问题。 uri 保持不变,但实际内容/图像发生了变化。我是这样解决的:
我创建了接受
dynamic
属性的自定义图像组件。这是因为我想更新特定图像 uri 的组件,而不是全部。
然后我使用 axios 来获取文件的响应头。这是因为响应标头中的 aws s3 给出了图像的最后更新时间。
最后,我在 uri 末尾连接一个字符串并更新状态,以便组件重新渲染。
import { StyleSheet, View, Image as NativeImage, ImageProps } from 'react-native'
import React, { useCallback, useEffect, useState } from 'react'
import { ActivityIndicator } from 'react-native-paper'
import axios from 'axios';
const Image = (props: ImageProps) => {
const [path, setPath] = useState("")
const checkFileMetadata = async () => {
try {
const response = await axios.head(props.source.uri)
setPath(props.source.uri + "?t=" + Date.now(response.headers?.["last-modified"]))
} catch (error) {
console.log("error", error)
}
}
useEffect(() => {
if (props.hasOwnProperty("dynamic")) {
checkFileMetadata()
}
}, [])
if (props.hasOwnProperty("dynamic")) {
return (
<View style={[styles.root, props.style]}>
{
path && (
<NativeImage
{...props}
source={{ ...props.source, uri: path }}
style={[styles.imageView, props.style]}
/>
)
}
<View style={styles.loaderRoot}>
<ActivityIndicator size={18} color='rgba(0,0,0,1)' />
</View>
</View >
)
}
return (
<View style={[styles.root, props.style]}>
<NativeImage
{...props}
style={[styles.imageView, props.style]}
/>
<View style={styles.loaderRoot}>
<ActivityIndicator size={18} color='rgba(0,0,0,1)' />
</View>
</View >
)
}
export default Image
const styles = StyleSheet.create({
root: {
overflow: "hidden"
},
imageView: {
zIndex: 2
},
loaderRoot: {
position: "absolute",
width: "100%",
height: "100%",
alignItems: "center",
justifyContent: "center",
backgroundColor: "rgba(0,0,0,0.1)",
zIndex: 1
}
})
使用这种方法的好处是我们可以利用React Native Image缓存机制。