Javascript 当我的组件卸载时,如何删除画布元素?
我有一个组件,它一直试图调整画布元素的大小(在窗口调整大小时),即使该组件卸载。因此,只有在卸载组件并调整屏幕大小后才会发生错误。之前,我使用setInterval绘制画布,因为画布显示动态数据。从那里,我可以使用clearInterval停止绘制画布。在这种情况下,我不需要setInterval,因为这个画布上的数据上传速度非常慢。这就是错误发生的地方Javascript 当我的组件卸载时,如何删除画布元素?,javascript,reactjs,canvas,Javascript,Reactjs,Canvas,我有一个组件,它一直试图调整画布元素的大小(在窗口调整大小时),即使该组件卸载。因此,只有在卸载组件并调整屏幕大小后才会发生错误。之前,我使用setInterval绘制画布,因为画布显示动态数据。从那里,我可以使用clearInterval停止绘制画布。在这种情况下,我不需要setInterval,因为这个画布上的数据上传速度非常慢。这就是错误发生的地方 componentDidMount() { this.circleOne(); //These functions draw the c
componentDidMount() {
this.circleOne(); //These functions draw the circle
this.circleTwo();
window.addEventListener("resize", () => {
this.circleOne(); //TypeError: Cannot read property 'getContext' of null
this.circleTwo();
}
);
}
您应该在方法中删除“resize”侦听器
为了做到这一点,您需要有一个对侦听器的引用(即它不能是匿名函数)
例如,您可以使侦听器成为另一个类方法,如下所示:
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.onResize = this.onResize.bind(this)
}
onResize() {
this.circleOne()
this.circleTwo()
}
componentDidMount() {
this.onResize() // Call to trigger the first draws
window.addEventListener('resize', this.onResize)
}
componentWillUnmount() {
window.removeEventListener('resize', this.onResize)
}
// Other methods...
}
您应该在方法中删除“resize”侦听器
为了做到这一点,您需要有一个对侦听器的引用(即它不能是匿名函数)
例如,您可以使侦听器成为另一个类方法,如下所示:
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.onResize = this.onResize.bind(this)
}
onResize() {
this.circleOne()
this.circleTwo()
}
componentDidMount() {
this.onResize() // Call to trigger the first draws
window.addEventListener('resize', this.onResize)
}
componentWillUnmount() {
window.removeEventListener('resize', this.onResize)
}
// Other methods...
}