0

모든 요청에 ​​대해 서버의 반응 구성 요소를 렌더링하는 기존 코드가 있는데, 이는 메모리 누수가 있음을 분명히합니다. 이 코드에 문제가 코너를 가지고 : 나는 모든에 this 개체가 새로운 청취자를 저장하는 요청 있다고 생각React Component with Memory Leak

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 요소는 쓰레기 때로 표시되지 않는되지 않습니다 구성 요소의 렌더링이 완료됩니다.

답변

2

구성 요소가 마운트 해제되기 전에 authChange 처리기의 바인딩을 해제해야합니다. componentWillUnmount에서이 작업을 수행 할 수 있습니다. 나중에 바인딩을 해제 할 수 있습니다

당신이 전달되는 첫 번째 소품을 사용하여 핸들러 함수를 만드는 때문에, 당신은 속성에 저장한다 : 나는 this.on을봤을 때 내가 생각했던 것을

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; 
    } 

당신은 jQuery를 사용하고 있을지 모르지만 그것이 어떻게되는지 분명하지 않다. 내 대답은 this.off을 사용하여 이벤트 리스너를 분리하지만 프레임 워크에있는 해당 메서드가 무엇이든 사용해야합니다.

+0

'renderToString()'함수가 완료되면 어쨌든'this' 컴포넌트가 쓰레기로 표시되지 않아야합니까? –

2

나는 componentDidMount로 기능을 이동 componentWillUnmount

중요에 정리를 추가 : componentWillMount서버클라이언트에 호출되지만 componentDidMount클라이언트 호출됩니다.

eventListeners, setInterval 또는 기타 기능을 청소해야하는 경우에는 componentDidMount에 넣으십시오. 서버는 componentWillUnmount에 전화하지 않으며 일반적으로 메모리 누수의 원인입니다.