Reactjs,如何在没有内存泄漏的情况下显示时钟
Reactjs, how to display clock without memory leak
我在 Reactjs (16.11.0) 中创建了一个简单的时钟,它告诉时间并每秒更新一次。请参阅下面的代码。
import React, {Component} from 'react';
import './clock.css'
class Clock extends Component {
constructor(props, context) {
super(props, context);
this.state = {
date: new Date()
};
}
componentDidMount() {
this.interval = setInterval(() => this.setState({date: new Date()}), 1000);
}
componentWillUnmount() {
clearInterval(this.interval)
}
render() {
let hour = ("0" + (this.state.date.getHours())).slice(-2);
let minute = ("0" + (this.state.date.getMinutes())).slice(-2);
let day = this.state.date.getDate();
let month = this.state.date.toLocaleString('nb', {month: 'long'});
return (
<section className={'clock'}>
<div>{hour + ':' + minute}</div>
<div className={'date'}>{day + '. ' + month}</div>
</section>
);
}
}
export default Clock;
在 Chrome 中监控任务管理器时,我可以看到选项卡内存随时间增加。
对于在 "kiosk" 设置下应该是 运行 的站点,这是不行的。我的 Rasperrypi 运行 几个小时后内存不足。
我的示例应用基于添加了此时钟组件的干净 'create-react-app'。
我能做些什么来防止这种内存泄漏?
更新
内存泄漏似乎只在 raspberrypi 上使用 chromium(和部分 FireFox)时发生,并且由于某种原因在使用此标志“--disable-gpu-program-cache”时减少了内存泄漏
您的应用中没有任何可能导致内存泄漏的内容。我还在 codesandbox with you app 中创建了一个示例,它每毫秒设置一次状态,并且应用程序选项卡的内存使用量不会随着时间的推移而增长(我检查了 Chrome 的任务管理器) .所以泄漏可能是由其他原因引起的。
我在 Reactjs (16.11.0) 中创建了一个简单的时钟,它告诉时间并每秒更新一次。请参阅下面的代码。
import React, {Component} from 'react';
import './clock.css'
class Clock extends Component {
constructor(props, context) {
super(props, context);
this.state = {
date: new Date()
};
}
componentDidMount() {
this.interval = setInterval(() => this.setState({date: new Date()}), 1000);
}
componentWillUnmount() {
clearInterval(this.interval)
}
render() {
let hour = ("0" + (this.state.date.getHours())).slice(-2);
let minute = ("0" + (this.state.date.getMinutes())).slice(-2);
let day = this.state.date.getDate();
let month = this.state.date.toLocaleString('nb', {month: 'long'});
return (
<section className={'clock'}>
<div>{hour + ':' + minute}</div>
<div className={'date'}>{day + '. ' + month}</div>
</section>
);
}
}
export default Clock;
在 Chrome 中监控任务管理器时,我可以看到选项卡内存随时间增加。 对于在 "kiosk" 设置下应该是 运行 的站点,这是不行的。我的 Rasperrypi 运行 几个小时后内存不足。
我的示例应用基于添加了此时钟组件的干净 'create-react-app'。
我能做些什么来防止这种内存泄漏?
更新
内存泄漏似乎只在 raspberrypi 上使用 chromium(和部分 FireFox)时发生,并且由于某种原因在使用此标志“--disable-gpu-program-cache”时减少了内存泄漏
您的应用中没有任何可能导致内存泄漏的内容。我还在 codesandbox with you app 中创建了一个示例,它每毫秒设置一次状态,并且应用程序选项卡的内存使用量不会随着时间的推移而增长(我检查了 Chrome 的任务管理器) .所以泄漏可能是由其他原因引起的。