首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法对已卸载的组件调用setState (或forceUpdate)。react-image-gallery上的内存泄漏

无法对已卸载的组件调用setState (或forceUpdate)。react-image-gallery上的内存泄漏
EN

Stack Overflow用户
提问于 2018-06-07 02:16:52
回答 1查看 535关注 0票数 0

我一直在尝试从npm包中实现react-image-gallery v0.8.7 (0.8.8有一个bug):https://github.com/xiaolin/react-image-gallery,并按照下面的example进行集成(我正在开发一个Meteor web应用程序):

代码语言:javascript
复制
class MyGallery extends Component {
    constructor(props) {
    super(props);
    this.state = {
      mediaSrc: [],
      isFullScreen: false
    };
  }

  componentWillMount() {
    const mediaSrc = this.props.myObject.pictures.map((picture) => {
      return { original: picture, thumbnail: picture };
    });
    this.setState({ mediaSrc });
  }

  _onImageClick(event) {
    if (this.state.isFullScreen) {
      this._imageGallery.exitFullScreen();
      this.setState({ isFullScreen: false });
    } else {
      this._imageGallery.fullScreen();
      this.setState({ isFullScreen: true });
    }
  }

  render() {
    return (
      <div className="dish row">
        <figure className="center col-12" >
          <div className="dish__preview_container">
            <ImageGallery
              ref={i => this._imageGallery = i}
              items={this.state.mediaSrc}
              onClick={this._onImageClick.bind(this)}
              showFullscreenButton={false}
              showIndex
              showPlayButton={false}
              showThumbnails={false}
            />
         </div>
      );
  }
}

MyGallery.propTypes = {
  myObject: PropTypes.object.isRequired,
}

}

对象myObject在图片数组中包含以下值:

代码语言:javascript
复制
[ 'https://media-cdn.tripadvisor.com/media/photo-s/05/6c/2b/9b/america-s-taco-shop.jpg',
  'https://www.cocinavital.mx/wp-content/uploads/2017/09/tostadas-de-tinga-de-pechuga-de-pollo-con-chipotle-video.jpg'
]

当渲染ImageGallery如预期那样显示时,但是当单击按钮aria-label=“上一张幻灯片”或aria-label=“下一张幻灯片”时,不会显示相应的图像,并在开发人员工具控制台上抛出以下异常:

代码语言:javascript
复制
Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
    in ImageGallery (created by MyGallery)
    in div (created by MyGallery)

有什么解决方案的建议吗?

更新:重置了componenteWillUmnount方法上的组件状态变量。删除了它,还尝试使用Meteor Reactive Dict而不是组件状态变量。不过,例外情况仍然存在。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-07 15:59:25

根据React Official Documentation的说法,您不应该在componentWillUnmount方法中调用setState(),因为您的组件永远不会被重新呈现。到目前为止,我只使用此方法删除在componentDidMount()中添加的事件侦听器。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50727041

复制
相关文章

相似问题

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