[英]React Component with Memory Leak
我有一段遺留代碼,它在每次請求時在服務器上呈現一個react組件,這顯然存在內存泄漏。 我已經解決了這個代碼的問題:
componentWillMount: function () {
var onLogin = this.props.onLogin || function () {},
onLogout = this.props.onLogout || function () {};
this.on('authChange', function () {
console.log('user authenticated:', this.state.isAuthenticated);
return this.state.isAuthenticated
? onLogin(this.state)
: onLogout(this.state);
}.bind(this));
},
我相信在每個請求中, this
對象都存儲了一個新的監聽器,但我不明白為什么在完成組件的渲染時, this
元素沒有被標記為垃圾。
在卸載組件之前,需要取消綁定authChange
處理程序。 您可以在componentWillUnmount
執行此操作。
由於您使用傳入的第一個道具創建處理函數,因此應將其保存到屬性中,以便以后可以取消綁定:
componentWillMount: function () {
var onLogin = this.props.onLogin || function () {},
onLogout = this.props.onLogout || function () {};
this.authChange = function () {
console.log('user authenticated:', this.state.isAuthenticated);
return this.state.isAuthenticated
? onLogin(this.state)
: onLogout(this.state);
}.bind(this);
this.on('authChange', this.authChange);
},
componentWillUnmount: function () {
this.off('authChange', this.authChange);
this.authChange = null;
}
需要注意的是,當我看到this.on
我想你可能會使用jQuery,但目前尚不清楚這將是這種情況。 我的回答使用this.off
來分離事件監聽器,但是您應該使用框架中相應方法的任何內容。
我會將您的函數移動到componentDidMount
並在componentWillUnmount
上添加清理
重要提示 : componentWillMount
被稱為服務器 端和客戶端 ,但componentDidMount
只調用客戶端上。
如果您正在使用eventListeners
, setInterval
或其他需要清理的函數,請將它們放在componentDidMount
。 服務器不會調用componentWillUnmount
,通常是內存泄漏的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.