React同步多张图片的onLoad

Synchronize the onLoad of multiple images with React

假设我有数量不详的图像正在使用 Andrew Farmer's example image component,它会检测每张图像何时加载:

import React from 'react';

class ImageWithStatusText extends React.Component {
  constructor(props) {
    super(props);
    this.state = { imageStatus: null };
  }

  handleImageLoaded() {
    this.setState({ imageStatus: 'loaded' });
  }

  handleImageErrored() {
    this.setState({ imageStatus: 'failed to load' });
  }

  render() {
    return (
      <div>
        <img
          src={this.props.imageUrl}
          onLoad={this.handleImageLoaded.bind(this)}
          onError={this.handleImageErrored.bind(this)}
          />
        {this.state.imageStatus}
      </div>
    );
  }
}
export default ImageWithStatusText;

使用 Flux 或 Redux 等框架,同步所有图像组件以检测所有图像何时加载完成的最简单方法是什么?

在 redux 中设置计数器可能是有意义的。对于每张图片,您可以分派一个动作以在 componentDidMount 中递增 imagesOnPage 计数器,然后分派一个动作以在 handleImageMounted 中递增 loadedImagesOnPage。对于 handleImageErrored,您可以减少 imagesOnPage。当imagesOnPage === loadedImagesOnPage时,加载所有图像。

一个更稳健的方法是为每个图像生成一个唯一的 ID,并有一个 images 化简器,每个键是唯一的 ID,值是它的状态: { image_1234: 'loading', image_111: 'loaded', image_12: 'error' } 您可以编写一些实用程序来查看该减速器并查看是否所有图像都处于 loaded 状态。