简体   繁体   English

如何在显示加载屏幕时加载图像反应本机

[英]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.现在我的渲染 function 中有一个“if”语句,它要么返回加载屏幕,要么返回页面的 rest。

I display the loading screen when I am fetching the URL for the profile photo and the name of user etc from firebase.当我从 firebase 获取个人资料照片和用户名等的 URL 时,我会显示加载屏幕。 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.但我不知道如何在图像从 URL 下载到我的应用程序时显示相同的加载屏幕,因为我是在 JSX 代码中下载的。

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.现在,当我从 firebase 等加载 URL 时,会显示加载屏幕,但随后我设置了 this.state。加载屏幕仍然需要几秒钟,因为加载屏幕仍然是假的,但加载屏幕仍然没有已经加载。

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.我将react-native-fast-image用于我的图像及其预加载function。

One method to do this is by fetching the image in the background, before the DOM is calling for it.一种方法是在 DOM 调用它之前在后台获取图像。

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} />);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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