1. ホーム
  2. javascript

[解決済み] react.jsのインスタンスvステート変数

2022-07-27 17:57:25

質問

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 .