简体   繁体   English

然后在promise外声明变量,然后在promise中初始化,然后访问promise

[英]Declare variable outside promise then, initialized inside promise then and access outside promise then

I need to access outState var which declared outSide class and then has set inside getData() func within promise then() func. 我需要访问声明为outSide类的outState var,然后在promise then()函数内的getData()函数内进行设置。

inside usrs func when loop has finished I need to access that but I cant. 循环完成后,在uss func内部,我需要访问它,但我不能。

let outState = {};
class A extends Component{
  getData(usr){
    db.collection('a/'+usr+'/bb').get().then(snap=>{
      for(i = snap.docs.length-1; i>=0; i--){
         outState[usr] = [...outState[usr], snap.docs[i].data()];
      }
    });
  }

  usrs(usrs){
    for(i = usrs.length-1; i>=0; i--){

       this.getData(usrs[i]);
       if(i===0){
        this.setState({ ...this.state, ...outState });
       }

    }
  }
}

I need to update state outside for loop, otherwise I can set the state inside promise func but It makes slow my app. 我需要为循环更新外部状态,否则可以在promise func内部设置状态,但这会使我的应用变慢。 Just I want to access it outside promise then function and then outside of loop update it. 我只是想在promise之外访问它,然后功能,然后在循环之外更新它。

I would recommend refactoring your component to something approximately like this, to keep everything a bit cleaner: 我建议将您的组件重构为大致类似的形式,以使所有内容保持整洁:

class A extends Component{
  constructor() {
    super();
    this.state = {
      usersData: {}      
    }  
  }

  getData(usr){
      let dataForUser = {};
      db.collection('a/'+usr+'/bb').get().then(snap=>{
        for(i = snap.docs.length-1; i>=0; i--){
           dataForUser[usr] = [...dataForUser[usr], snap.docs[i].data()];
        }
      });
      return dataForUser;
    }

    usrs(usrs){
      let data = {};
      for(i = usrs.length-1; i>=0; i--){
         let userData = getData(usrs[i]);

         if(i===0){
          data = {...data, ...userData};
         }
      }
      this.setState({usersData: data});
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM