2015-11-19 55 views
0

我有一個SPA,允許用戶上傳數據和查看基於數據的計算。Reactjs設計與昂貴的API調用

我使用父組件每2秒輪詢一次,通過AJAX獲取數據列表中的每個項目。我遍歷列表中的每個項目,這些項目調用一個子響應組件,這會使昂貴的API調用檢索計算結果並將其顯示在表中。

這是子組件代碼:

var DisplayRow = React.createClass({ 

    getInitialState: function(){ 
     return (
      {data: [] } 
      ); 

    }, 

    componentDidMount: function(){ 
     this.loadData() 
    }, 

    loadData: function(){ 
     $.ajax({ 
       url: "http://127.0.0.1:8000/api/tables/" + this.props.columns + "/stats/", 
       dataType: 'json', 
       cache: false, 
       success: function(data){ 
        this.setState({data: data}); 
        console.log("mounted"); 

       }.bind(this), 
       error: function(xhr, status, err) { 
        console.error(this.props.url, status, err.toString()); 
       }.bind(this) 
      }); 
    }, 

/* 
    shouldComponentUpdate: function(nextProps, nextState){ 
     console.log(nextProps.columns) 
     console.log(this.props.columns) 
     return nextProps.columns !== this.props.columns; 
    }, 
    */ 

    render: function(){ 


     var rows = this.state.data.map(function(item){ 
     var titles = [] 
     var vals = [] 
     for(var key in item){ 
      if (item.hasOwnProperty(key)){ 
       titles.push(key) 
       vals.push(item[key]) 
       } 
     } 
     return (
      <table className="table-hover table-bordered"> 
      <tbody> 
      <DisplayStuff stuff={titles} /> 
      <DisplayStuff stuff={vals} /> 
      </tbody> 
      </table> 
      ); 

     }); 


     return (
      <div className="yep"> 

      <h2> {this.props.name} </h2> 
       {rows} 
      </div> 
      ); 

什麼是設計它,因此名單上的投票是細的好辦法,但除非初始列表是昂貴的API調用只會發生一次(改變,例如更多的數據被添加)?

我玩弄了shouldComponentUpdate,但在渲染髮生之前我調用了API,所以仍然會調用,並且如果在初始數據加載之後刷新頁面,則表不會呈現。

回答

1

您可以撥打和緩存父組件中昂貴的API調用。然後只需將該數據作爲道具傳遞給DisplayRow

+0

有沒有特定的方法來緩存它?我的父組件正在輪詢第一個API調用,我隨後使用它來創建更昂貴的調用。 – dl8

+0

沒有具體的方法。父母緩存它是合適的。 – Jason