IT story

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

hot-time 2020. 8. 6. 07:51
반응형

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업데이트 될 때마다 ( setState주석에서 제안한 대로만 수행해야 함 ) React는 호출 render하고 실제 DOM을 필요한대로 변경합니다.

의 값은 timeout구성 요소의 렌더링에 영향을 미치지 않으므로에 포함되어서는 안됩니다 state. 그것을 넣으면에 불필요한 호출이 발생합니다 render.


@ssorallen이 말한 것 외에도 handleLeave가 호출되기 전에 구성 요소 마운트 해제를 처리해야합니다.

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

반응형