【发布时间】:2015-11-19 22:08:38
【问题描述】:
我有一个 SPA,允许用户上传数据并查看基于数据的计算。
我使用每 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,所以仍然会进行调用,而且如果我在初始数据加载后刷新页面,则不会渲染表格。
【问题讨论】:
标签: javascript ajax reactjs