반응형
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
반응형
'IT story' 카테고리의 다른 글
Windows 서비스에서 사용하기위한 최상의 타이머 (0) | 2020.08.06 |
---|---|
ASP.Net 양식에 제출 된 게시물 데이터 읽기 (0) | 2020.08.06 |
여러 페이지 앱에서 React 사용 (0) | 2020.08.06 |
mysql에서 같은 테이블에서 어떻게 두 번 조인합니까? (0) | 2020.08.06 |
PostgreSQL-기존 권한으로 사용자를 빠르게 삭제하는 방법 (0) | 2020.08.06 |