jquery - ajax成功内循环中的多个ajax调用
问题描述
下面代码的问题是组件在完成其余调用之前首先呈现,因此 DOM 是空的。循环中的第二个 ajax 将触发 50 次,因为一位经理下有 50 名直接下属。第二个 ajax 调用是获取直接报告者的显示名称,因为第一个 ajax 调用只提供data.d.DirectReports.results中的电子邮件。那么,如何让所有的 ajax 调用先完成,然后渲染组件以在 DOM 中显示数据呢?
public componentDidMount(){
this.getReportees();
}
getReportees = () => {
var reportees = [];
var reactHandler = this;
var drReportess = [];
$.ajax({
url: this.siteUrl+"/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='" + encodeURIComponent(accountName) + "'&$select=DirectReports",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" }
}).done((data)=>{
let length: Number = data.d.DirectReports.results.length > 0 ? data.d.DirectReports.results.length : 0;
if(length>0){
$.each(data.d.DirectReports.results, function (i, value: string) {
reportees.push(value);
});
$.each(reportees,function(i,value){
$.ajax({
url: this.siteUrl+"/_api/SP.UserProfiles.PeopleManager/GetUserProfilePropertyFor(accountName=@v,propertyName='PreferredName')?@v='" + encodeURIComponent(value) + "'",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" }
}).done((data)=>{
drReportess.push({
DisplayName: data.d.GetUserProfilePropertyFor,
LoginName: value
})
})
})
reactHandler.setState({
directReportees: drReportess
})
console.log(reactHandler.state.directReportees);
}
})
}
public render(): React.ReactElement<IDashboardProps> {
console.log('Render');
return(
<table className="ms-Table course-table">
<thead>
<tr>
<th>Team Members</th>
</tr>
</thead>
<tbody>
{this.state.directReportees && this.state.directReportees.map((item, i) => {
return [
<tr>
<td>{item.DisplayName}</td>
</tr>
]
})}
</tbody>
</table>
);
}
这里先渲染(console.log),然后再加载数据,所以表是空的。
解决方案
从 onInit 调用你的 this.getReportees() 函数,它在渲染之前运行
public onInit(): Promise<void> {
await this.getReportees();
}
希望这能解决您的问题。
推荐阅读
- android - AndroidRuntime:致命例外:androidmapsapi-ZoomTableManager
- react-native - 在我处理表单验证时导航服务不起作用
- python - 如何通过matplotlib分离绘制的图形
- java - java.lang.NoClassDefFoundError:如何获取类路径?
- azure-data-factory - Azure 数据工厂 (ADF) 是否支持链接服务 Azure Cosmos DB(表 API)?
- ruby-on-rails - Mailgun:如何在 ruby 中批量验证电子邮件?
- string - 检查字符串是否以 Rust 中的数字开头的更简单方法?
- r - R Studio - 获取滚动月份的总和
- pandas - 如何对数据框中有日期的列进行排序?
- javascript - 使用 OR 运算符显示零而不是 NaN