首页 > 解决方案 > 加载所有图像后更新组件的状态

问题描述

加载完所有图像后,我正在尝试更新组件的状态。这个想法是能够同时向用户显示网格中的所有图像,而不是他们看到每个图像一次加载一个。

这是我加载图像的组件。

import React from 'react';
import { useState } from "react";

//Storage to show the images on the grid
var imagesSources = [];

/* 
 * ==============================================================
 * Component to show a grid random images
 * ==============================================================
 */
 function RandomImageGrid(props) {

  var childrenLoaded = 0;

  const [loading, isLoading] = useState(true);
  console.log("loading state: " + loading);
  console.log("Loading images...");

  //When all the <img> have loaded, then update the state so we know loading is done
  const handleChildLoad = () =>  {

    childrenLoaded++;
    console.log("child: " + childrenLoaded);

    if(childrenLoaded === props.gridSize){
      isLoading(false);
      console.log("loading state: " + loading);
      console.log("All images have loaded");
    }
  };

  //an array of image paths for the src attribute in the <img> tags  
  imagesSources = ['cats_01.jpg', 'cats_02.jpg', 'cats_03.jpg', 'cats_04.jpg', 'cats_05.jpg', 'cats_06.jpg', 'cats_07.jpg', 'cats_08.jpg', 'cats_09.jpg']

   return (
    
    <div key={props.imageType} className="catcha-images">
      { imagesSources.map((source, gridPosition) => {
        return(
          <div>
            <img
              src={source} 
              onLoad={ () => {handleChildLoad()}}
            />
          </div>
        )
      }) }
    </div>
    )
  }

export default RandomImageGrid;

我想我不了解 React 生命周期,因为当前代码给了我这样的输出

loading: true
RandomImageGrid.js:42 Loading images...
RandomImageGrid.js:46 child: 1
RandomImageGrid.js:46 child: 2
RandomImageGrid.js:46 child: 3
RandomImageGrid.js:46 child: 4
RandomImageGrid.js:46 child: 5
RandomImageGrid.js:46 child: 6
RandomImageGrid.js:46 child: 7
RandomImageGrid.js:46 child: 8
RandomImageGrid.js:46 child: 9
RandomImageGrid.js:50 loading: true
RandomImageGrid.js:51 All images have loaded
RandomImageGrid.js:41 loading: false
RandomImageGrid.js:42 Loading images...

我所期望的,会更像:

loading: true
RandomImageGrid.js:42 Loading images...
RandomImageGrid.js:46 child: 1
RandomImageGrid.js:46 child: 2
RandomImageGrid.js:46 child: 3
RandomImageGrid.js:46 child: 4
RandomImageGrid.js:46 child: 5
RandomImageGrid.js:46 child: 6
RandomImageGrid.js:46 child: 7
RandomImageGrid.js:46 child: 8
RandomImageGrid.js:46 child: 9
RandomImageGrid.js:50 loading: false
RandomImageGrid.js:51 All images have loaded

所以状态并没有更新我的预期,并且似乎发生了第二次渲染。但我不确定为什么或如何发生这种情况。

谢谢你的帮助。

标签: javascriptreactjsasynchronousstate

解决方案


推荐阅读