【问题标题】:Synchronize the onLoad of multiple images with React用 React 同步多张图片的 onLoad
【发布时间】:2016-05-07 16:56:42
【问题描述】:

假设我有未指定数量的图像正在使用 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 之类的框架,同步所有图像组件以检测所有图像何时完成加载的最简单方法是什么?

【问题讨论】:

    标签: javascript reactjs flux redux


    【解决方案1】:

    在 redux 中设置计数器可能是有意义的。对于每个图像,您可以发送一个操作来增加componentDidMount 中的imagesOnPage 计数器,然后发送一个操作来增加handleImageMounted 中的loadedImagesOnPage。对于handleImageErrored,您可以减少imagesOnPageimagesOnPage === loadedImagesOnPage时,所有图片都加载完毕。

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

    【讨论】:

      猜你喜欢
      • 2018-04-06
      • 2018-02-21
      • 1970-01-01
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 2015-01-31
      • 1970-01-01
      相关资源
      最近更新 更多