2015-11-19 74 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