2016-03-23 24 views
1

我已經使用Reactjs爲我的項目創建了聊天應用程序。對於最新的更新,我需要每次點擊服務器。對於此需求,我使用了setInterval方法。這種方法是正確的嗎?reactjs中componentDidMount的設置時間間隔是正確的方法嗎?

例如,

componentDidMount:function(){ 
    setInterval(function(){ 
    $.ajax({ 
     url:this.props.url, 
     dataType:"JSON", 
     type:"GET", 
     success:function(data){ 
     this.setState({data:data}); 
     }.bind(this) 
    }); 
    }, 1000); 
} 

回答

3

是的,這很好,但使用的setTimeout遞歸通常優選。它可以確保您不會一次執行多個請求,但需要一秒鐘才能完成。

您也可能想立即運行一次。

最後,您需要清除componentWillUnmount中的超時值。

componentDidMount: function(){ 
    function tick(){ 
    $.ajax({ 
     url: this.props.url, 
     dataType: "JSON", 
     type: "GET", 
     success:function(data){ 
     this.setState({data: data}); 

     this.timer = setTimeout(tick, 500); 
     }.bind(this) 
    }); 
    }; 
    tick(); 
}, 
componentWillUnmount: function() { 
    clearTimeout(this.timer); 
} 
+1

在'componentWillUnmount'中調用'clearTimeout()'很重要,但還不夠。可能會發生組件被卸載,超時被清除,但有一個未完成的Ajax請求會稍後成功,並且會嘗試在卸載的組件上調用setState()。 – iaretiga

+0

@fakerainbrigand謝謝。這就是我想要的.. – Sathya

+0

@iaretiga你的意思是清晰的數據值正確嗎? like,this.setState({data:「」}); – Sathya

相關問題