我有一个组件,即使在组件卸载时也会不断尝试调整 Canvas 元素的大小(在窗口调整大小时)。因此,该错误仅在组件卸载并调整屏幕大小后发生。以前,我使用 setInterval 来绘制 Canvas ,因为 Canvas 显示动态数据。从那里,我可以使用clearInterval来停止绘制 Canvas 。在这种情况下,我不需要 setInterval,因为此 Canvas 上的数据上传速度非常慢。这就是错误发生的地方...
componentDidMount() {
this.circleOne(); //These functions draw the circle
this.circleTwo();
window.addEventListener("resize", () => {
this.circleOne(); //TypeError: Cannot read property 'getContext' of null
this.circleTwo();
}
);
}
最佳答案
您应该删除 React's componentWillUnmount 中的“调整大小”监听器方法。
为此,您需要引用监听器(即它不能是匿名函数)。
例如,您可以将监听器设置为另一个类方法,如下所示:
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...
}
关于javascript - 当我的组件卸载时,如何删除 Canvas 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48656282/