【问题标题】:Declare variable outside promise then, initialized inside promise then and access outside promise then然后在promise外部声明变量,然后在promise内部初始化,然后在promise外部访问
【发布时间】:2019-03-06 00:15:02
【问题描述】:

我需要访问outState var,它声明了outSide 类,然后在getData() func 中设置了promise then() func。

在 usrs 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 });
       }

    }
  }
}

我需要在 for 循环之外更新状态,否则我可以在 promise func 中设置状态,但这会使我的应用程序变慢。 只是我想在 Promise 之外访问它然后运行它,然后在循环之外更新它。

【问题讨论】:

  • 为什么需要在课外?这看起来可能会在以后引起问题
  • 因为有超过 100 个用户如果在 promise 函数中设置状态,它将在循环内更新状态超过 100 次,这使得应用程序在执行 getData 函数时变慢
  • 听起来你解决了错误的问题。将您的状态更新合并为一个批量更新并执行一次。

标签: javascript reactjs react-native google-cloud-firestore


【解决方案1】:

我建议将您的组件重构为类似这样的东西,以保持一切更清洁:

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});
    }
  }

【讨论】:

  • 不幸的是,这仅返回一个 emty 对象 {}
  • 问题是当我们在promise then() 中初始化dataForUser 时,我们无法在promise then() 函数之外使用更新后的值访问它
猜你喜欢
  • 1970-01-01
  • 2017-12-15
  • 1970-01-01
  • 2021-06-23
  • 2023-03-09
  • 1970-01-01
  • 2016-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多