首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React应用程序在内存中累积Base64编码的图像。可能的原因是什么?

React应用程序在内存中累积Base64编码的图像。可能的原因是什么?
EN

Stack Overflow用户
提问于 2021-03-18 01:25:09
回答 1查看 44关注 0票数 0

我的react应用程序中有一个屏幕,在左侧有一个项目列表,在右侧面板上显示所选项目的描述。每个项目都有一组图像(通常是每个项目3到4个图像)。当选择一个项目时,我向后端发出GET请求,以加载该项目的图像。然而,我注意到了巨大的内存增量,似乎每次选择一个项目之前加载的图像都没有从内存中释放出来:

我渲染的图像如下:

代码语言:javascript
复制
<img src={`data:image/png;base64,${image.fileContent}`}/>

因此,我决定将img标记替换为自定义组件,以查看它们是否正在被卸载。所以我实现了这个组件:

代码语言:javascript
复制
export class Image extends React.PureComponent<IImageProps, IImageState> {

  componentWillUnmount() {
    console.info('Unmounting image: ' + this.props.alt + ', size: ' + (this.props.source.length / 1000) + 'kb');
  }

  render() {
    const { source, alt, title, height, width, className, pinchToZoom } = this.props;

    return pinchToZoom ?
      <PinchZoomPan maxScale={2} position="center">
        <img src={source} alt={alt} title={title} width={width} height={height} className={className}/>
      </PinchZoomPan>
      :
      <img src={source} alt={alt} title={title} width={width} height={height} className={className}/>;
  }
}

组件工作正常,我看到日志显示正在卸载映像组件。

代码语言:javascript
复制
Unmounting image: ID_1582, size: 65.67kb
Unmounting image: ID_1584, size: 64.886kb
Unmounting image: ID_1586, size: 66.142kb
Unmounting image: ID_1588, size: 65.462kb

然而,内存仍然在增加,我仍然看到每一组新的图像被添加到Chrome DevTools >应用程序>图像部分的列表中。在我刷新页面并等待几秒钟后,这个问题似乎消失了,内存显著下降,并恢复正常。

顺便说一下,图像作为Base64编码的字符串加载并存储在组件状态中;每次选择新项目时,状态更新如下:

代码语言:javascript
复制
this.mounted && this.setState({ loadingImages: false, images: response.data });

任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2021-03-26 23:04:14

我可以阻止JS内存增长的唯一方法是,当用户从列表中选择不同的项目时,将加载图像的组件的状态重置为其默认状态。

代码语言:javascript
复制
componentDidMount() {
  this.state = initialState; // holds the images as a string[]
}

componentDidUpdate(prevProps: Readonly<IProductsScreenProps>, 
    prevState: Readonly<IProductsScreenState>, snapshot?: any) {

  // When switching to another item then:
  if (prevProps.selectedItem && this.props.selectedItem &&
  (prevProps.selectedItem.id !== this.props.selectedItem.id)) {

    // Reset this screen to it's initial state:
    this.mounted && this.setState(initialState);

    this.loadItemImages();
  }
}

由于我将所选项目作为道具接收,因此我使用componentDidUpdate函数来检查所选项目何时发生更改。

我仍然不能理解为什么当我尝试用一个空数组重置状态下的图像时,它不起作用。

代码语言:javascript
复制
this.mounted && this.setState({ images: [] });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66678199

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档