[英]React: what happens to a function when component stop being rendered
我在一个组件中定义了一个函数,它在安装组件时启动并保持运行。 当组件停止渲染或卸载时,该函数会发生什么?
class MyComponent extends React.Component<> {
_count = () => {
console.log('a second passed');
setTimeout(1000, this._count);
}
componentDidMount() {
_count();
}
}
除非它被清除,否则计时器将继续运行,因此您需要在componentWillUnmount
中清除它,该componentWillUnmount
用于“执行任何必要的清理......例如使计时器无效”:
class MyComponent extends React.Component {
_count = () => {
console.log('a second passed');
this.countTimer = setTimeout(this._count, 1000);
}
componentDidMount() {
_count();
}
componentWillUnmount() {
clearTimeout(this.countTimer);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.