2016-10-20 51 views
0

我有一段遺留代碼,它會在每個請求上呈現服務器上的響應組件,這使得顯然存在內存泄漏。我有角的問題到這個代碼:有內存泄漏的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元素沒有被標記爲垃圾時組件的渲染完成。

回答

2

在卸載組件之前,您需要解除綁定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來分離事件監聽器,但是您應該使用框架中相應的方法。

+0

但'renderToString()'函數完成時,不應該將'this'組件標記爲垃圾嗎? –

2

我會提出你的函數爲componentDidMountcomponentWillUnmount

重要添加清理:componentWillMount稱爲服務器客戶,但componentDidMount只叫客戶上。

如果您使用的是eventListeners,setInterval或其他需要清理的功能,請將它們放入componentDidMount。服務器不會調用componentWillUnmount,通常是內存泄漏的原因。