簡體   English   中英

react.js中的實例v狀態變量

[英]Instance v state variables in react.js

在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); 
     },
    ...
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM