javascript - 无法在未安装的组件上调用 setState(或 forceUpdate)。react-image-gallery 上的内存泄漏
问题描述
我一直在尝试从这个 npm 包中实现 react-image-gallery v0.8.7(0.8.8 有一个错误): https ://github.com/xiaolin/react-image-gallery 并按照示例集成为如下(我正在开发一个 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 而不是组件状态变量。不过,例外仍然存在。
解决方案
根据React Official Documentation,你不应该调用方法setState()
,componentWillUnmount
因为你的组件永远不会被重新渲染。迄今为止,我只使用这种方法来移除在componentDidMount()
.
推荐阅读
- flutter - 如何使用颤振 firebase_ml_vision 裁剪面部轮廓?任何其他方式来实现这一目标?谢谢
- python - Python CrashCourse:生成多个随机游走
- sql - 将此查询转换为视图 - 不允许声明/设置
- sql - 在 Oracle DB 中过滤联接
- java - 如何使用 Single Live Event 打开包含 Room 数据的对话框片段?
- python - 如何将不和谐频道与python链接
- azure-sql-database - 从 Azure SQL 弹性作业步骤中发送电子邮件
- c++ - WinHttpAddRequestHeaders:在标头中发送证书时为87 - C++
- ethereum - 更新实时智能合约
- javascript - D3 json() 函数适用于本地文件,但不适用于将本地 var 设置为 json