Instance v state variables in react.js

前端 未结 2 592
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 15:01

In react.js, is it better to store a timeout reference as an instance variable (this.timeout) or a state variable (this.state.timeout)?

React.createClass({
          


        
相关标签:
2条回答
  • 2020-12-07 15:24

    In addition to what @ssorallen said, you should also remember to handle the component unmounting before your handleLeave is called.

    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); 
         },
        ...
    });
    
    0 讨论(0)
  • 2020-12-07 15:35

    I suggest storing it on the instance but not in its state. Whenever state is updated (which should only be done by setState as suggested in a comment), React calls render and makes any necessary changes to the real DOM.

    Because the value of timeout has no effect on the rendering of your component, it shouldn't live in state. Putting it there would cause unnecessary calls to render.

    0 讨论(0)
提交回复
热议问题