【问题标题】:Multiple ajax calls in loop inside ajax successajax成功内循环中的多个ajax调用
【发布时间】:2020-09-19 07:50:11
【问题描述】:

以下代码的问题是组件在完成其余调用之前先呈现,因此 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),然后加载数据,所以表是空的。

【问题讨论】:

  • 为什么不在循环之前清除状态的directReportees 数组,并在完成时让Ajax 调用将每个reportee 对象附加到状态(通过setState())?这样,结果是否异步输入就无关紧要了。
  • @kmoser:你的意思是说在循环内的 done 函数中推送 setState() ?我已经试过了,它没有帮助。
  • 没有帮助意味着它不起作用?还是报错?
  • 对不起,我的意思是,即使将 setstate() 放在 done 函数中,结果也是一样的,dom 是空的,并且在 dom 加载后 ajax 正在完成。 ``` public render(): React.ReactElement { console.log("render");返回(
    )} ``` 。这里先在控制台日志中渲染,然后是 this.state.directReportees。

标签: jquery reactjs ajax rest spfx


【解决方案1】:

从渲染前运行的 onInit 调用 this.getReportees() 函数

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

希望这能解决您的问题。

【讨论】:

    猜你喜欢
    • 2017-02-25
    • 1970-01-01
    • 2018-07-28
    • 2011-03-15
    • 2017-06-11
    • 2013-08-07
    • 1970-01-01
    • 2012-03-03
    • 2010-12-14
    相关资源
    最近更新 更多