programing

react.js의 인스턴스 v 상태 변수

lastmoon 2023. 3. 13. 20:45
반응형

react.js의 인스턴스 v 상태 변수

react.js에는 타임아웃 참조를 인스턴스 변수(this.timeout)와 상태 변수(this.state.timeout) 중 어느 것으로 저장하는 것이 좋습니까?

React.createClass({
     handleEnter: function () {
         // Open a new one after a delay
         var self = this;
         this.timeout = setTimeout(function () {
             self.openWidget();
         }, DELAY);
     },
     handleLeave: function () {
        // Clear the timeout for opening the widget
        clearTimeout(this.timeout); 
     }
    ...
})

또는

React.createClass({
     handleEnter: function () {
         // Open a new one after a delay
         var self = this;
         this.state.timeout = setTimeout(function () {
             self.openWidget();
         }, DELAY);
     },
     handleLeave: function () {
        // Clear the timeout for opening the widget
        clearTimeout(this.state.timeout); 
     }
    ...
})

이 두 가지 방법 모두 효과가 있습니다.나는 단지 하나를 다른 하나에 사용하는 이유를 알고 싶을 뿐이다.

인스턴스에는 저장할 것을 권장합니다만, 그 인스턴스에는 저장할 수 없습니다.state.언제든지state갱신(댓글에 제시된 대로만 실행), React 호출render실제 DOM 에 필요한 변경을 가합니다.

그 가치가timeout컴포넌트 렌더링에 영향을 주지 않습니다.존재하지 않아야 합니다.state거기에 두면, 불필요한 콜이 발생합니다.render.

@ssorallen이 말한 것 외에 handle Leave를 호출하기 전에 컴포넌트의 마운트 해제 처리를 잊지 마십시오.

React.createClass({
     handleEnter: function () {
         // Open a new one after a delay
         this._timeout = setTimeout(function () {
             this.openWidget();
         }.bind(this), DELAY);
     },
     handleLeave: function () {
        // Clear the timeout for opening the widget
        clearTimeout(this._timeout); 
     },
     componentWillUnmount: function(){
        // Clear the timeout when the component unmounts
        clearTimeout(this._timeout); 
     },
    ...
});

언급URL : https://stackoverflow.com/questions/25207703/instance-v-state-variables-in-react-js

반응형