首页 > 解决方案 > 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),然后再加载数据,所以表是空的。

标签: jqueryreactjsajaxrestspfx

解决方案


从 onInit 调用你的 this.getReportees() 函数,它在渲染之前运行

public onInit(): Promise<void> {
  await this.getReportees();
}

希望这能解决您的问题。


推荐阅读