React implements the principle analysis of the three stages of loading, loading, completion, loading failure

React implements the principle analysis of the three stages of loading, loading, completion, loading failure

Recently I wrote in my blog that in the project list, I found that there were many pictures here, and the loading would be slow at the beginning, so I wanted to use a loading picture to take up space. At the same time, if the image fails to load, then the error image is displayed instead of the original error, which is ugly.

Effect

insert image description here

Principle Analysis

This is a component, a component for displaying pictures. Just change the URL address of the img tag. Yes, that's right. Change the address directly in Vue, and Vue will update the data responsively.

Picture of the event

There are many events for images, for example, onload , onerror , etc. The onload event will be called as soon as the image is loaded, regardless of whether the loading is successful or failed. The onerror method is called when the image is not displayed. From the comparison of these two methods, we can see that we need to use onload to load the image at the beginning, and the image can succeed or fail, etc.

Component Code

import { ImgHTMLAttributes } from "react";

/**
 * Image placeholder component properties*/
export interface IImagProps<T> extends ImgHTMLAttributes<T> {
  /**
   * Loading images */
  loadingImg?: string,
  /**
   * Failed to load the image */
  errorImg?: string,
 /**
  * The address where the picture is normally displayed*/
  src: string,
}

import React, { useState } from 'react'
// The following two are to import the default imagesimport loadImg from './../../../assets/imgs/loading/load.gif';
import errorImg from './../../../assets/imgs/loading/error.png'
export default function Img(props: IImagProps<any>) {
  // Image address const [src, setSrc] = useState(props.loadingImg as string)
  // Is it the first time to load? If you don't use this, it will be loaded twice const [isFlag, setIsFlag] = useState(false)
  /**
   * Image loading completed*/
  const handleOnLoad = () => {
    // Determine if it is the first time to load if (isFlag) return;
    // Create an img tag const imgDom = new Image();
    imgDom.src = props.src;
    // Image loading is complete, use the normal image imgDom.onload = function () {
      setIsFlag(true)
      setSrc(props.src)
    }
    // Image loading failed, use image placeholder imgDom.onerror = function () {
      setIsFlag(true)
      setSrc(props.errorImg as string)
    }
  }
  
  return (
    <>
      <img src={src}
        onLoad={handleOnLoad}
        style={{
          height: 'inherit',
        }}
      ></img>
    </>
  )
}
// Set the default style for loading images and failed images Img.defaultProps = {
  loadingImg: loadImg,
  errorImg: errorImg
}

PS: Let's take a look at the loading effect before the img image is loaded in React

  • I have such a requirement in React, that is, I hope to display the loading animation effect before the image is loaded, and render the image after the image is loaded.
  • Let's talk about the specific ideas first, and then talk about the practical application
  • Implementation ideas:
// Suppose I want to load these three web images var imglist = ['http://example.com/demo1.png','http://example.com/demo2.png','http://example.com/demo3.png']
// images is used to store the loaded images var images = []
imglist.forEach(el=>{
	var image = new Image()
	image.src = el
	image.onload = function(){
		// Indicates that the image has been loaded. // Add the loaded image to images images.push(image)
	}
})

//Judge when the component is rendered if(images.length === 3){
	// This means that all three web page images have been loaded and can be rendered. // Render loaded images. }else{
	// This means that the web page images have not been fully loaded yet, so the loading animation effect will continue. // loading animation effect}

Specific implementation examples

import React from 'react'
import { Carousel, Spin } from 'antd' // use antd
// Create the Home component class Home extends React.Component{
	constructor(props){
		super(props)
		this.state = {
			imglist: [
				{
					id: '01',
					src: 'http://example.com/demo1.png',
					alt: 'demo1'
				},
				{
					id: '02',
					src: 'http://example.com/demo2.png',
					alt: 'demo2'
				},
				{
					id: '03',
					src: 'http://example.com/demo3.png',
					alt: 'demo3'
				}
			],
			images: []
		}
	}
	UNSAFE_componentWillMount(){
		// Perform operations before rendering var { imglist } = this.state
		var images = []
		imglist.forEach(el=>{
			var image = new Image()
			image.src = el.src
			image.onload = ()=>{
				images.push(image)
				this.setState({
					images
				})
			}
		})
	}
	render(){
		var { imglist, images } = this.state
		if(images.length === 3){
			// This means that all three images have been loaded and can be rendered. return (
				<div className='common-body'>
					<Carousel autoplay>
						{imglist.map(el=>(
							<img src={el.src} key={el.id} alt={el.alt} />
						))}
					</Carousel>
				</div>
			)
		}else{
			// The image has not been fully loaded yet, so the loading animation effect should be displayed at this time return (
				<div className='common-loading'>
					<Spin tip='Loading...' size='large'></Spin>
				</div>
			)
		}
	}
}
export default Home

This method is still more useful

The above is the detailed content of the principle analysis of the three stages of react's implementation of image loading, loading completed, and loading failed. For more information about react's image loading completion, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Several implementation solutions for lazy loading of React routes
  • React Native code example based on FlatList pull-down refresh pull-up load
  • React Native custom pull-down refresh pull-up loaded list example
  • React-native ListView pull down to refresh and pull up to load implementation code
  • React-router 4 on-demand loading implementation and principle detailed explanation
  • Detailed explanation of using require.ensure() to load ES6 components on demand in React development

<<:  Perfect Solution for No rc.local File in Linux

>>:  The easiest way to install MySQL 5.7.20 using yum in CentOS 7

Recommend

Instructions for using the --rm option of docker run

When the Docker container exits, the file system ...

MySQL log trigger implementation code

SQL statement DROP TRIGGER IF EXISTS sys_menu_edi...

avue-crud implementation example of multi-level complex dynamic header

Table of contents Preface Background data splicin...

How to deploy Spring Boot using Docker

The development of Docker technology provides a m...

Detailed explanation of putting common nginx commands into shell scripts

1. Create a folder to store nginx shell scripts /...

A brief discussion on CSS height collapse problem

Performance For example: HTML: <div class=&quo...

MySQL series tutorials for beginners

Table of contents 1. Basic concepts and basic com...

Sample code for implementing horizontal infinite scrolling with pure CSS3

The examples in this article are all written in s...

Practice of using Vite2+Vue3 to render Markdown documents

Table of contents Custom Vite plugins Using vite-...

How MySQL handles implicit default values

Some students said that they encountered the prob...

Tips to prevent others from saving as my web page and copying my site

Nowadays, copying websites is very common on the I...

JavaScript source code for Elimination

JavaScript to achieve the source code download ad...

Quickly solve the problem of slow and stuck opening of input[type=file]

Why is it that when the input tag type is file an...