2015-09-29 40 views
3

所以我創建了以下的mixin:輪詢在不工作作出反應JS混入

var Polling = { 

    startPolling: function() { 
     var self = this; 

     setTimeout(function() { 
      self.poll(); 

      if (!self.isMounted()) { 
       return; 
      } 

      self._timer = setInterval(self.poll(), 15000); 
     }, 1000); 
    }, 

    poll: function() { 
     if (!this.isMounted()) { 
      return; 
     } 

     var self = this; 
     console.log('hello'); 
     $.get(this.props.source, function(result) { 
      if (self.isMounted()) { 
       self.setState({ 
        error: false, 
        error_message: '', 
        users: result 
       }); 
      } 
     }).fail(function(response) { 
      self.setState({ 
       error: true, 
       error_message: response.statusText 
      }); 
     }); 
    } 
} 

注意console.log('hello');poll功能。根據這個邏輯,我應該每15秒看一次。

現在讓我們來看一個反應成分:

//= require ../../mixins/common/polling.js 
//= require ../../mixins/common/state_handler.js 
//= require ../../components/recent_signups/user_list.js 

var RecentSignups = React.createClass({ 

    mixins: [Polling, StateHandler], 

    getInitialState: function() { 
     return { 
      users: null, 
      error_message: '', 
      error: false 
     } 
    }, 

    componentDidMount: function() { 
     this.startPolling(); 
    }, 

    componentWillUnmount: function() { 
     if (this._timer) { 
      clearInterval(this._timer); 
      this._timer = null; 
     } 
    }, 

    shouldComponentUpdate: function(nextProps, nextState) { 
     if (this.state.users   !== nextState.users || 
      this.state.error   !== nextState.error || 
      this.state.error_message !== nextState.error_message) { 

      return true; 
     } 

     return false; 
    }, 

    renderContents: function() { 
     if (this.state.users === null) { 
      return; 
     } 

     return (
      <div> 
       <ul> 
        <UserList users={this.state.users} /> 
       </ul> 
      </div> 
     ); 
    }, 

    render: function() { 
     return (
      <div> 
      {this.loading()} 
      {this.errorMessage()} 
      {this.renderContents()} 
      </div> 
     ) 
    } 
}); 

RecentSignupsElement = document.getElementById("recent-signups"); 

if (RecentSignupsElement !== null) { 
    ReactDOM.render(
     <RecentSignups source={ "http://" + location.hostname + "/api/v1/recent-signups/" } />, 
     RecentSignupsElement 
    ); 
} 

在這裏,我們在componetDidMount功能我打電話this.startPolling看到頁面加載時,我在1秒之後看到的是:

hello 
hello 
  • A)其(poll fucntion)一些如何被稱爲兩次oO。
  • B)其(poll函數)永遠不會再被調用。

我分開查詢的原因是我可以在同一頁面上的其他組件中使用它,而不是重複的代碼。

非常簡單的問題:

爲什麼以及如何解決這個問題?我需要它輪詢15秒,當poll第一次被調用時,我只應該看到hello

回答

6

在此行中調用self.poll(),其結果將是定時器:

self._timer = setInterval(self.poll(), 15000); 

而是傳遞函數:

self._timer = setInterval(self.poll, 15000); 
0

作爲另一種選擇,本着「你的代碼不工作?只是使用別人的代替!「,react-async-poll是一個方便的組件包裝,您可以用於輪詢。