javascript - 当我的组件卸载时,如何删除 Canvas 元素?

标签 javascript reactjs canvas

我有一个组件,即使在组件卸载时也会不断尝试调整 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/

相关文章:

javascript - 是否可以从网页内部使用 Chrome 远程调试协议(protocol)?

javascript - 运行 react 应用程序时出现 Chokidar UNKNOWN 错误

javascript - 为什么我的 React 组件不渲染 HTML,但日志正确?

c# - 将 Canvas 转换为位图图像并裁剪为路径

javascript - 即使在调整大小后也下载原始 Canvas

javascript - 同步 Node.js API 和 AWS Lambda

javascript - 返回数组中的每个 DOM 元素

php - 将变量从 php while 循环传递给 javascript 函数

javascript - 如何在 React 应用中导入 highcharts 子模块

javascript - 将文本工具添加到 Paint App HTML5 Canvas