【问题标题】:How could I write this function so it doesn't setState within the foreach everytime我怎么能写这个函数,所以它不会每次都在 foreach 中设置状态
【发布时间】:2021-08-16 12:00:33
【问题描述】:

该函数收集 SPO 中项目的角色分配 PrincipalId。然后,我使用 foreach 用这些 PrincipalId 的 Title 填充状态。这一切都很好,但效率低下,我相信有比多次渲染更好的方法。

private _permJeChange = async () => {
    if(this.state.userNames){
      this.setState({
        userNames: []
      });
    }
    var theId = this.state.SelPermJEDD;
    var theId2 = theId.replace('JE','');

    var info = await sp.web.lists.getByTitle('MyList').items.getById(theId2).roleAssignments();
    console.log(info, 'info');
   
    var newArr = info.map(a => a.PrincipalId);
    
    console.log(newArr, 'newArr');
    // const userIds = [];
    // const userNames = [];
    // const userNameState = this.state.userNames;
    newArr.forEach(async el => {
     
      try {
        await sp.web.siteUsers.getById(el).get().then(u => {
          this.setState(prevState => ({
            userNames: [...prevState.userNames, u.Title]
          }));
          // userNames.push(u.Title);
          //  userIds.push(el);
           
         });
       } catch (err) {
         console.error("This JEForm contains a group");
       }

     });

    
  }

我在其中留下了旧代码,让您了解我的尝试。我最初尝试使用局部变量数组const userNames = [],但在本地甚至全局声明它会在每次填充数组时清除数组!所以这不好。

PS。有一个 try catch 的原因是处理任何分配有权限组的 SPO 项目。 RoleAssignments() 请求不能处理组,只能处理用户。

【问题讨论】:

    标签: reactjs sharepoint-online spfx


    【解决方案1】:

    创建一个 Promise 数组并等待它们全部解决,然后进行一次状态更新。

    const requests = info.map(({ PrincipalId }) => 
      sp.web.siteUsers.getById(PrincipalId).get().then(u => u.Title)
    );
    
    try {
      const titles = await Promise.all(requests);
      this.setState(prevState => ({
        userNames: prevState.userNames.concat(titles),
      }));
    } catch (err) {
      console.error("This JEForm contains a group");
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 2011-01-19
      • 2020-12-23
      • 1970-01-01
      • 2021-11-16
      相关资源
      最近更新 更多