简体   繁体   English

在反应中,只有在所有数据可用后才显示组件?

[英]In react, how to display component only after all data is available?

I have a component that displays images.我有一个显示图像的组件。 The component has a menu bar as well.该组件也有一个菜单栏。

During initially server request, this component always shows the menu bar for a split second because the actually image is not loaded yet.在最初的服务器请求期间,此组件始终显示菜单栏一瞬间,因为实际图像尚未加载。

How to display the menu bar only after the image is ready?如何仅在图像准备好后才显示菜单栏?

EDITED:编辑:

I can determine when the URLs to the images are loaded and available.我可以确定图像的 URL 何时加载并可用。 But how to tell if the actually image itself is ready?但是如何判断实际图像本身是否已准备好?

Actually I have a workaround, which might be valid in your case: you can add loading for some seconds until images is rendered successfully, I hope this help you实际上我有一个解决方法,这可能对您的情况有效:您可以添加加载几秒钟,直到图像成功呈现,我希望这对您有所帮助

You can have a loading state set to true by default like so:您可以将加载 state 默认设置为 true,如下所示:

const [loading, setLoading] = useState(true);

After you have all your data fetched, you set it to false like so:获取所有数据后,将其设置为 false ,如下所示:

setLoading(false)

And you render will be something like this:你渲染将是这样的:

return (<div>
  {loading ? <p>loading...</p> : <MyComponent/>}
</div>)

You can use partial rendering for example例如,您可以使用部分渲染

import React, { useEffect, useState } from 'react';

    function App() {
    
    
      const [data, setData] = useState(null);
    
      useEffect(()=>{
        setData(true);
      }, []);
    
      return (
        <div>
          {data && <div> after data is not null this will be visible</div>}
        </div>
      );
    }
    export default App;

You can set a state as below and load the menu based on this value;您可以如下设置 state 并根据此值加载菜单;

const [ImageLoaded, setImageLoaded] = useState(false);

You can do it like this:你可以这样做:

function YourComponent () {
    
    const [imgLoaded, setImgLoaded] = useState(false);
   
    const handleImgLoad = () => {
        setImgLoaded(true);
    }

    return(
        <>
            <img onLoad={handleImgLoad} src="..." alt="..." />
            {imgLoaded ? <MenuBar /> : <></>}
        </>
    );
}

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

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