[英]React JS memory leak with periodic calculations using setInterval
我正在尝试定期运行计算(每 5 秒)并使用setInterval
计时器使用计算值更新组件的 state。 我所看到的是updateCalculation()
function确实每 5 秒被调用一次,但是当使用 Chrome 开发工具监视 memory 的使用情况时,它只会在每次调用setInterval
时不断增长。 memory 似乎从未发布过。
快照 1:
快照 2:
定期运行计算的可能解决方法是什么? 我对 React 还是很陌生,我真的不确定我做错了什么。
class MyComponent extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
calculated: []
};
}
componentDidMount() {
this.calculationUpdater = setInterval(() => this.updateCalculation(), 5000);
}
componentWillUnmount() {
clearInterval(this.calculationUpdater);
}
// Memory leak here
// The function that gets called by setInterval to calculate data and update the state
updateCalculation() {
let data = [];
for (let i = 0; i < 60000; i++) {
data.push({x: i, y: i, z: i});
}
this.setState({
calculated: data
});
}
render() {
return (
<React.Fragment>
<Child calc={this.state.calculated} />
</React.Fragment>
);
}
}
目前我没有对Child
组件做任何特别的事情。 这是它的样子:
class Child extends React.PureComponent {
render() {
return (
<div></div>
);
}
}
编辑:检查以下帖子: JavaScript setInterval() 方法是否导致 memory 泄漏?
您没有清除间隔,因为您没有正确设置或读取 state。 因此,如果您的组件不断被安装和卸载,您可以设置一个新的间隔,但不要清除卸载时的间隔。
this.calculationUpdater = setInterval(() => this.updateCalculation(), 5000);
这应该是
const calculationUpdater = setInterval(() => this.updateCalculation(), 5000);
console.log(calculationUpdater )
this.setState({calculationUpdater : calculationUpdater})
您访问 state 如下:
console.log(this.state.calculationUpdater);
clearInterval(this.state.calculationUpdater);
我唯一能建议的是尝试从 PureComponents 切换到 Components; 我注意到我的初始快照对于 PureComponents 来说比较滞后,尽管无论哪种方式我的结果都不像你的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.