reactjs - react : Show loading spinner while images load

标签 reactjs image spinner loading

我有一个 React 应用程序,它在 useEffect 中调用我的 API,返回一个用作 imy 图像 src 的 URL 列表。

我正在使用 react-loader-spinner 在加载图像时显示加载旋转器组件。

我在 useState 中有一个 loading 变量来确定图像是否正在加载。

我不知道如何停止显示加载微调器并在图像全部加载后显示它们。

这是我的代码:

Photos.jsx

import React, { useState, useEffect, Fragment } from 'react'
import Loader from 'react-loader-spinner';
import { getAllImages } from '../../services/media.service';
import Photo from '../common/Photo';

const Photos = () => {
  const [photos, setPhotos] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
      setLoading(true);
      getAllImages()
        .then(results => {
          setPhotos(results.data)
          console.log(results.data)
        })
        .catch(err =>{
          console.log(err)
        })
  }, [])

  const handleLoading = () => {
    setLoading(false)
  }

  return ( 
    <Fragment>
      <div className="photos">
          { loading ? 
            <Fragment>
              <Loader
                height="100"    
                width="100"
              />
              <div>Loading Joe's life...</div>
            </Fragment>
            :
            photos.map((photo, index) => (
                index !== photos.length - 1 ? 
                <Photo src={photo.src} key={photo.id} /> :
                <Photo src={photo.src} key={photo.id} handleLoad={handleLoading}/>
            ))
          }
      </div>
    </Fragment>
   );
}

export default Photos;

Photo.jsx

import React from 'react'

import './Photo.css';

const Photo = (props) => {
  return ( 
    <div className="photo">
      <img src={props.src} alt={props.alt} onLoad={props.handleLoad}/>
      <div className="caption">
        Photo caption
      </div>
    </div>
   );
}

export default Photo;

我尝试使用 onLoad 作为我的最后一个项目,但它永远不会被调用,因为 loading 由于旋转器仍然显示而永远不会设置回 false。

对此提供一些帮助将不胜感激。谢谢

最佳答案

onLoad 从未被调用的原因是因为您从未在 DOM 中拥有图像,因此不要有条件渲染,而是有条件地将 display 属性设置为 none & block。

下面是一个简单的示例,说明如何等待所有图像加载。

Safe to assume the image with the largest file size would most likely be the last to load

当然不是!!,加载图像所需的时间并不总是取决于大小、缓存或服务器负载会影响这些。

const {useState, useEffect, useRef} = React;

const urls = [
  "https://placeimg.com/100/100/1" ,
  "https://placeimg.com/100/100/2" ,
  "https://placeimg.com/100/100/3"
];

function Test() {
  const [loading, setLoading] = useState(true);
  const counter = useRef(0);
  const imageLoaded = () => {
    counter.current += 1;
    if (counter.current >= urls.length) {
      setLoading(false);
    }
  }
  return <React.Fragment>
    <div style={{display: loading ? "block" : "none"}}>
       Loading images,
    </div>
    <div style={{display: loading ? "none" : "block"}}>
      {urls.map(url => 
        <img 
          key={url}
          src={url}
          onLoad={imageLoaded}/>)}
    </div>
  </React.Fragment>;
}

ReactDOM.render(<React.Fragment>
  <Test/>
</React.Fragment>, document.querySelector('#mount'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="mount"></div>

关于reactjs - react : Show loading spinner while images load,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56902522/

相关文章:

html - 图像悬停始终显示在同一位置

java - 如何在同一个 HTTP 请求中以字节形式发送图像并一起发送 json 数据?

java - Android:捕获的图像未显示在图库中(媒体扫描器 Intent 不起作用)

java - 安卓- "A spinner does not support item click events. Calling this method will raise an exception."

android - 避免在 Spinner 中显示选定的文本

node.js - 我无法从我的 REACT 应用程序的 azure 应用程序服务配置中读取环境变量

javascript - 链接参数不会在 JSX 中呈现( react )

node.js - 当我在服务器端更新模式时,中继/GraphQL 模式缓存不更新

reactjs - 不要在某些路线上渲染某些组件

java - HoloEverywhere Spinner OnClickListener() 错误