2016-10-26 97 views
0

我在其他問題中查找並嘗試了所有內容。仍然無法解決我的內存泄漏。這是代碼。從本質上講,它從服務器獲取JSON文件並相應地更新表。它每5秒循環一次AJAX呼叫。React Ajax setInterval內存泄漏

在此AJAX調用中發生內存泄漏。 任何幫助將是偉大的。

LoadDataTable:函數(){

$.ajax({ 
    url: "***************************.json", 
    dataType: 'json', 
    cache: false, 
    timeout: 5000, 
    success: function(data) { 
    this.setState({temp1:data[2].field3}), 
    this.setState({temp2:data[2].field5}), 
    this.setState({temp3:data[2].field25}), 
    this.setState({temp4:data[2].field26}); 

    if(data[2].field3 > 9 || data[2].field5 >9||data[2].field5>9 ||data[2].field26>9){ 
     document.location.href='#/' 
    } 
    else{ 
     //console.log("Stopped playing"); 
    } 
    setTimeout(this.LoadDataTable, 5000); 


}.bind(this), 
    error: function(request, status, err) { 

    //request.abort(); 
    console.log(request); 
    setTimeout(this.LoadDataTable, 5000); 

    }.bind(this), 

}) 

}, 
componentDidMount: function() { 
    this.LoadDataTable(); 
    //this.setInterval(this.LoadDataTable, 100);// Call a method on the mixin 
}, 
+0

這不是答案,但您不需要多次調用setState,傳遞一個整個對象一次 –

+0

我會說,一般來說,您不希望您的React組件負責製作這些AJAX請求。理想情況下,您將使用Redux(或某種外部狀態機制)發出請求,然後您的應用程序會將新數據作爲「prop」傳遞給組件。使用該體系結構的一個副作用是它可以避免你遇到的內存泄漏 - 另外它更符合React「最佳實踐」。 – arthurakay

回答

0

嘗試移動你的成功和錯誤的功能出了一個名爲函數是這樣的:

$.ajax({ 
    url: "***************************.json", 
    dataType: 'json', 
    cache: false, 
    timeout: 5000, 
    success: this.successTimeout, 
    error: this.errorTimeout, 
}) 

componentDidMount: function() { 
    this.LoadDataTable(); 
    //this.setInterval(this.LoadDataTable, 100);// Call a method on the mixin 
}, 

successTimeout(data) { 
    this.setState({temp1:data[2].field3}), 
    this.setState({temp2:data[2].field5}), 
    this.setState({temp3:data[2].field25}), 
    this.setState({temp4:data[2].field26}); 

    if(data[2].field3 > 9 || data[2].field5 >9||data[2].field5>9 ||data[2].field26>9){ 
    document.location.href='#/' 
    } 
    else{ 
    //console.log("Stopped playing"); 
    } 

    setTimeout(this.LoadDataTable, 5000); 
}.bind(this), 

errorTimeout(request, status, err) { 
    //request.abort(); 
    console.log(request); 
    setTimeout(this.LoadDataTable, 5000); 
}.bind(this) 

此外,您可能要考慮使用fetch API 。請確保include the polyfill用於瀏覽器兼容性