【问题标题】:Async await on component did mount组件上的异步等待确实挂载了
【发布时间】:2018-01-29 14:29:39
【问题描述】:

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

  componentDidMount = () => {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.setState({user: user})
      }
    });
    this.props.retrieveMatches(this.state.user.uid)
  }

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

  async componentDidMount = () => {
    await firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.setState({user: user})
      }
    });
    this.props.retrieveMatches(this.state.user.uid)
  }

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

【问题讨论】:

    标签: javascript reactjs asynchronous setstate


    【解决方案1】:

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

    componentDidMount = () => {
      firebase.auth().onAuthStateChanged((user) => {
        if (user) {
          this.setState({user: user}, () => { 
            this.props.retrieveMatches(this.state.user.uid); 
          })
        }
      });
    }
    

    问候

    【讨论】:

      【解决方案2】:

      我理解这种混淆,但该行使用回调而不是 Promises,因此您不应该使用 async/await

      应该是:

      componentDidMount = () => {
        firebase.auth().onAuthStateChanged((user) => {
          if (user) {
            this.setState({user: user}, () => { this.props.retrieveMatches(this.state.user.uid); })
          }
        });
      }
      

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

      这个

      promise.then((result) => {...}).catch((error) => {});
      

      会变成

      try {
        const result = await promise();
      } catch (error) {
        // do stuff
      }
      

      【讨论】:

        【解决方案3】:

        您不应该使反应生命周期方法异步。

        在外部执行一个异步等待方法作为辅助函数,然后将其导入:

        在帮助文件中:

        async asynchronousFn() {
            const result = await (your asynchronous code)
            return result
        }
        

        在组件中:

        componentDidMount() {
            asynchronousfn().then(result => this.setState({ statekey: result }));
        }
        

        【讨论】:

        • 记住异步函数返回一个promise,你不想把promise放在state中,你想把result放在state中。
        • 您好,Ben hi 并没有真正将生命周期方法设为异步,请看这篇简短的帖子medium.com/front-end-hacking/… 我在这里看到的是,为了将来使用,您的代码更加干净
        【解决方案4】:

        使用setState API 上的回调函数,您将解决问题。链接中是 setState 的文档,因此您可以看到 setState 及其接受的参数。

        我认为此时您不需要 Promise 的异步,因为您看到 onAuthStateChanged 返回一个函数,而不是一个承诺

        componentDidMount = () => {
          firebase.auth().onAuthStateChanged((user) => {
            if (user) {
              this.setState({user: user}, () => { this.props.retrieveMatches(this.state.user.uid); 
            })
           }
         });  
        }
        

        【讨论】:

          猜你喜欢
          • 2018-11-12
          • 1970-01-01
          • 2019-03-06
          • 1970-01-01
          • 2018-02-13
          • 1970-01-01
          • 1970-01-01
          • 2014-01-09
          • 1970-01-01
          相关资源
          最近更新 更多