我一直在尝试从这个npm包中实现react-image-gallery v0.8.7(0.8.8有一个bug):https://github.com/xiaolin/react-image-gallery并在example之后集成如下(我正在开发一个Meteor网络应用程序):
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'
]
当渲染ImageGallery时,按预期显示,但是当点击按钮aria-label =“Previous Slide”或aria-label =“Next Slide”时,不显示相应的图像并抛出以下异常开发人员工具控制台:
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 t而不是组件状态变量。但是例外仍然存在。
答案 0 :(得分:3)
根据React Official Documentation,您不应在setState()
方法中调用componentWillUnmount
,因为您的组件永远不会被重新呈现。到目前为止,我只使用此方法删除componentDidMount()
中添加的事件侦听器。