我想做以下几件事,并记住它实际上对我有用.我的问题是会发生什么,是否可以从非异步componentDidMount() func调用async usrs() func?

let outState = {};
class A extends Component{
  componentDidMount(){
   this.usrs(usrs);
  }
  getData(usr){
    return 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()];
         if(i === 0) return outState;
      }
     return false;
    });
  }

  async usrs(usrs){

   let os = {}, data = {};

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

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

    }

  }

}

推荐答案

当我们需要呼叫并等待async函数或Promise时,我们使用await

这是你的componentDidMount.then

componentDidMount(){
    this.usrs(usrs).then(() => {
        // Your functions completely finished
    })
    .catch(err => {
        // There was an error
    });

    this.doSomethingElse();
}

React-native相关问答推荐

REACT-Native-Render-html中所有文本的默认字体大小

如何在 react-navigation v6 中更改标题高度

React-Native:无法从我的 android 应用程序打开设备设置

React Native 的 Firebase 初始错误(无法读取未定义的属性getItem)

开发 React Native Apps 时如何在 Android 模拟器窗口中重新加载?

React Native 白色黑屏问题

react-native 链接仅适用于一个项目(Android 或 iOS)

React Native 错误找不到模块metro-config/src/defaults/blacklist

React Native 无法读取 index.android.delta

如何在 react-native 上自动聚焦下一个 TextInput

从数据源添加/删除列表视图项时为它们设置动画

如何在 React Native 中创建对角线边框?

react-native Http 拦截器

渲染时获取未定义不是 React Native 中的对象

react-native Bottom Up drawer

Firebase 3.3 实时数据库坚持使用 React Native 0.32 Making a connection attempt

在 React Native Navigator 中的组件之间传递值

在 OPTIONS 响应后使 fetch API 与 CORS 一起工作

由于对 sourcetree 的 husky 预推送,Git 推送失败

React Native - 如何从推送通知中打开路由