【问题标题】:Show image only if the image is loaded from the database仅当从数据库加载图像时才显示图像
【发布时间】:2021-08-30 06:40:44
【问题描述】:

我有问题。我正在数据库中搜索图片是否存在。如果图像不存在,则设置“无图像”图像。如果图像可用,则显示数据库中的当前图像。

我现在想做的是显示一个加载微调器,只有当数据库中的图像可用并且数据库中的图像仍在加载时才会显示。

我现在有以下问题:当我从数据库加载图像时,一切都合适。但是,一旦我没有来自数据库的图像,就会显示“无图像”并且还会显示加载微调器。如果 dataPic 不为零且图像尚未加载,我现在怎么能说只显示加载微调器?

import React, { useEffect, useState, useRef } from 'react'
import axios from 'axios'
import { Spinner } from 'react-spinners-css';

import nophoto from '../../../data/images/nophoto.png'

const id = (window.location.pathname).split("-")[1];

function Team() {

    const [imgLoaded, setImgLoaded] = useState(false);  

    const [dataPic, setDataPic] = useState(null);
    const getPhoto = () => {
        axios
            .get(`${process.env.REACT_APP_API_URL}/photo-${id}`,

        )
            .then((res) => {
                if (res.status === 200) {
                    var parts = res.data.split(",");
                    var result = parts[parts.length - 1];
                    setDataPic(result);
                }
            })
            .catch((error) => {
                console.log(error);
            });
    }

    useEffect(() => {
        getPhoto();
    }, []);

    return (
        <div>
            {/*here ist the problem*/}
            {imgLoaded && dataPic === null ? null :
                <div>
                    <Spinner color="#5869FF" style={{ left: "50", right: "50", top: "50", bottom: "50", }} />
                    <p>Is loading...</p>
                </div>
            }
            {
                dataPic === null ?
                    <img src={nophoto} alt="hi"/>
                    :
                    <img src={`data:image/png;base64,${dataPic}`} alt="hi" onLoad={() => setImgLoaded(true)} />

            }


    )
}

export default Team

【问题讨论】:

    标签: reactjs image if-statement


    【解决方案1】:
    .then((res) => {
       if (res.status === 200) {
         var parts = res.data.split(",");
         var result = parts[parts.length - 1];
         setDataPic(result);
       }
     setImgLoaded(false)
    })
    .catch((error) => {
       setImgLoaded(false)
       console.log(error);
    });
    

    使用下面的代码显示加载

    {!imgLoaded ?  <React.Fragment>
        { dataPic === null ?
           <img src={nophoto} alt="hi"/>
            :
          <img src={`data:image/png;base64,${dataPic}`} alt="hi" onLoad={() => 
              setImgLoaded(true)} />
        }
    </React.Fragment>
    :<div>
      <Spinner color="#5869FF" style={{ left: "50", right: "50", top: "50", bottom: "50", }} />
      <p>Is loading...</p>
     </div>}
    

    【讨论】:

    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多