代码之家  ›  专栏  ›  技术社区  ›  Yajairo87 Streets Of Boston

无法对未安装的组件调用setState(或forceUpdate)。React图像库内存泄漏

  •  0
  • Yajairo87 Streets Of Boston  · 技术社区  · 6 年前

    我一直在尝试实现react图像库v0.8.7(0.8.8有 bug )从这个npm包: https://github.com/xiaolin/react-image-gallery 并按照 example 如下所示(我正在开发Meteor Web应用程序):

    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 在图片数组中包含以下值:

    [ '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'
    ]
    

    当呈现图像库时,如预期所示,但是当单击按钮aria label=“上一张幻灯片”或aria label=“下一张幻灯片”时,不会显示相应的图像,并在开发人员工具控制台上引发以下异常:

    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 Dic 而不是组件状态变量。不过,例外依然存在。

    1 回复  |  直到 6 年前
        1
  •  3
  •   Jose Ramos    6 年前

    根据 React Official Documentation ,你不应该打电话 setState() 在里面 componentWillUnmount 方法,因为您的组件永远不会被重新呈现。到目前为止,我只使用此方法删除 componentDidMount() .