简体   繁体   中英

How do I load an image while displaying loading screen react native

I am trying to load the profile photo on my page before removing the loading screen, but can't figure out how. Right now I have an "if" statement in my render function that either returns the loading screen or the rest of the page.

I display the loading screen when I am fetching the URL for the profile photo and the name of user etc from firebase. But I can't figure out how to also display the same loading screen while the image is downloaded into my app from the URL because I download it in the JSX code.

Here is the code in my render statement:

render(){
    if (this.state.loading == true) {
        return (
            //returns jsx of a full page loading screen
        )
    }
    return (
        <View style={{ justifyContent: 'center', alignItems: 'center', marginTop: 50, marginBottom: 50 }}>
            <Image style={{ width: 150, height: 150, borderRadius: 500 }} source={{ uri: this.state.userimage }} />
        </View>
    )
}

This code is simplified but this is basically what I am doing.

Right now the loading screen shows up when I am loading the URL from firebase etc, but then I set this.state.loading to false and the loading screen goes away, but the Image still takes a few seconds to load because it wasn't already loaded.

Could somebody tell me how to pre-load the image or some other easy way to load the image while my loading screen is still on then display it without delay?

Thank you!

I use react-native-fast-image for my images and their preload function.

One method to do this is by fetching the image in the background, before the DOM is calling for it.

Below is some simple code that demonstrates this functionality.

import React from 'react';

const IMAGE_URL = "https://via.placeholder.com/150";

const preloadImage = (url) => {
  return fetch(url);
}

export const App = (props) => {
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    // comment out this line and the image is not loaded until it is needed in the dom
    preloadImage(IMAGE_URL);

    setTimeout(() => setLoading(false), 3000);
    }, []
  );

  return (loading ? <span>Loading</span> : <img src={IMAGE_URL} />);
}

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