组件上的异步等待已挂载

Async await on component did mount

这是我的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 行

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

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

问候

我理解混淆,但该行使用回调而不是 Promises,所以你不应该使用 async/await

应该是:

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

您可以使用 async/await 替换 promises then 和 catch calls

这个

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

会变成

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

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

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

在辅助文件中:

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

在组件中:

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

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

我认为此时您不需要 Async of Promise,因为您看到 onAuthStateChanged return 一个函数,而不是一个 promise

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