这是我的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行
发布于 2018-01-29 22:32:15
您需要使用.setState()的回调函数:
componentDidMount = () => {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({user: user}, () => {
this.props.retrieveMatches(this.state.user.uid);
})
}
});
}问候
发布于 2018-01-29 22:33:31
我理解你的困惑,但是这行使用的是回调,而不是承诺,所以你不应该使用async/await
它应该是:
componentDidMount = () => {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({user: user}, () => { this.props.retrieveMatches(this.state.user.uid); })
}
});
}您可以使用async/await替换promises并捕获调用
这个
promise.then((result) => {...}).catch((error) => {});会变成
try {
const result = await promise();
} catch (error) {
// do stuff
}发布于 2018-01-29 22:47:36
你不应该让react生命周期方法异步。
在外部执行async await方法作为辅助函数,然后导入它:
在帮助程序文件中:
async asynchronousFn() {
const result = await (your asynchronous code)
return result
}在组件中:
componentDidMount() {
asynchronousfn().then(result => this.setState({ statekey: result }));
}https://stackoverflow.com/questions/48503579
复制相似问题