2014-08-08 28 views
79

In react.js, è meglio memorizzare un riferimento di timeout come variabile di istanza (this.timeout) o una variabile di stato (this.state.timeout)?Istanza v variabili di stato in react.js

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

o

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

entrambi questi approcci funzionano. Voglio solo sapere i motivi per usare l'uno sull'altro.

+11

Dal [documentazione] (http://facebook.github.io/react/docs/component-api.html): * "** ** MAI mutano' this.state' direttamente, come chiamare 'setState()' può in seguito sostituire la mutazione che hai fatto. Tratta 'this.state' come se fosse immutabile." * –

+6

Suggerimento: Usa l'autobinding di React: 'this.timeout = setTimeout (this.openWidget, DELAY);' – David

+1

A cosa dovrebbe essere impostato DELAY? – justingordon

risposta

119

Suggerisco di memorizzarlo nell'istanza ma non nel suo state. Ogni volta che viene aggiornato state (che dovrebbe essere eseguito solo da setState come suggerito in un commento), React chiama render e apporta le eventuali modifiche necessarie al DOM reale.

Poiché il valore di timeout non ha alcun effetto sul rendering del componente, non dovrebbe vivere in state. Mettendolo lì causerebbe chiamate non necessarie a render.

9

Oltre a ciò che @ssorallen ha detto, è necessario ricordare di gestire lo smontaggio del componente prima che venga chiamato il comando 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); 
    }, 
    ... 
}); 
+1

grazie per il promemoria – brendangibson

Problemi correlati