我正在尝试在加载所有图像后更新组件的状态。我们的想法是能够同时向用户显示网格中的所有图像,而不是每次看到每个图像加载一个。
这是我的组件,用于加载图像。
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
所以状态不会按照我的预期更新,并且似乎发生了第二次渲染。但我不确定为什么或如何发生这种情况。
感谢您的帮助。