简体   繁体   中英

React Native Images On Android Never Reload When Uri Doesn't Change

Despite uploading a new image to an s3 hosted url, the <Image> component will not update the image if the uri does not change. This is a problem for Android only as far as I can tell, because for iOS you can use the cache: 'reload' prop.

I have resorted to this solution:

<Image 
  source={uri: imageUrlFromS3 + '?time=' + new Date(), cache: 'reload'}
  style={width: 100, height: 100}
/>

By adding a meaningless query to the url, the component recognizes that the uri has changed, which then refreshes the updated image. Similarly, I have tried this by changing the key to be a new Date(). This seems like horrible for performance, due to the aggressive rerendering.

It seems that this has been a problem for a long time .

I have seen some answers that require using another package .

Is there another solution to this problem that doesn't require using another package?

You just have to do it like this:

source={uri: imageUrlFromS3 + '?' + new Date()}

You can substring the unix timestamp such that it could re-render every N milliseconds.

For example, source={uri: imageUrlFromS3 + '?' + Date.now().toString().substring(0,10) + "000"... source={uri: imageUrlFromS3 + '?' + Date.now().toString().substring(0,10) + "000"...

would mean it would re-render every 1000 milliseconds = 1 second.

Instead of concatenating the current Date prop, what you can do is create a state that takes the value of a random number whether you execute the query (the one that updates the image) and concatenate that to the uri, like this:

// state to notify the updating image process
const [onUpdateImage, setOnUpdateImage] = useState(Math.random())

// Function that updates the image
const updateImageQuery = () => {
  ...
  setOnUpdateImage(Math.random())
}

//Image Display:
<Image style={{ width: 133, height: 133, }}
     source={{
        uri: image_URL + "?" + onUpdateImage               
       }}
 />

This way you can optimize the App performance and do the image re-rendering only when it's necessary. If the image is exposed in other screens, you can create onUpdateImage as a Context and use it globally.

Hope this helps you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM