首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异步等待组件did装载

异步等待组件did装载
EN

Stack Overflow用户
提问于 2018-01-29 22:29:39
回答 4查看 3K关注 0票数 5

这是我的componentDidMount方法。我想设置当前用户的状态,然后在设置该用户时调用函数。我该怎么做呢?

代码语言:javascript
复制
  componentDidMount = () => {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.setState({user: user})
      }
    });
    this.props.retrieveMatches(this.state.user.uid)
  }

我尝试过使用async/await,但在这里我没有正确使用它:

代码语言:javascript
复制
  async componentDidMount = () => {
    await firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.setState({user: user})
      }
    });
    this.props.retrieveMatches(this.state.user.uid)
  }

基本上,我想在第7行调用props函数之前等待第2-6行

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-01-29 22:32:15

您需要使用.setState()的回调函数:

代码语言:javascript
复制
componentDidMount = () => {
  firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      this.setState({user: user}, () => { 
        this.props.retrieveMatches(this.state.user.uid); 
      })
    }
  });
}

问候

票数 4
EN

Stack Overflow用户

发布于 2018-01-29 22:33:31

我理解你的困惑,但是这行使用的是回调,而不是承诺,所以你不应该使用async/await

它应该是:

代码语言:javascript
复制
componentDidMount = () => {
  firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      this.setState({user: user}, () => { this.props.retrieveMatches(this.state.user.uid); })
    }
  });
}

您可以使用async/await替换promises并捕获调用

这个

代码语言:javascript
复制
promise.then((result) => {...}).catch((error) => {});

会变成

代码语言:javascript
复制
try {
  const result = await promise();
} catch (error) {
  // do stuff
}
票数 2
EN

Stack Overflow用户

发布于 2018-01-29 22:47:36

你不应该让react生命周期方法异步。

在外部执行async await方法作为辅助函数,然后导入它:

在帮助程序文件中:

代码语言:javascript
复制
async asynchronousFn() {
    const result = await (your asynchronous code)
    return result
}

在组件中:

代码语言:javascript
复制
componentDidMount() {
    asynchronousfn().then(result => this.setState({ statekey: result }));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48503579

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档