【发布时间】:2020-08-08 21:11:36
【问题描述】:
我正在使用 firebase 作为身份验证工具开发一个简单的 react js 应用程序。这是我的 app.js
***some imports
class App extends React.Component {
constructor() {
super();
this.state = {
currentUser: null
}
}
unsubscribeFromAuth = null;
componentDidMount() {
this.unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {
if(userAuth){
const userRef = await createUserProfileDocument(userAuth);
userRef.onSnapshot(snapShot => {
this.setState({
currentUser: {
id: snapShot.id,
...snapShot.data()
}
},() => {console.log(this.state)});
});
}
else
{
this.setState({ currentUser: userAuth });
}
});
}
componentWillUnmount() {
this.unsubscribeFromAuth();
}
render() {
return (
<div>
<h1>{this.state.currentUser.email}</h1>
</div>
)
}
}
export default App
问题是当我运行项目时,它会给出这个错误currentUser is null ,如果我在 app.jsx 中删除<h1>{this.state.currentUser.email}</h1>,控制台会在延迟 5 或 6 秒后记录状态,并且该日志包含我想要的内容,这是当前用户。
这就是我使用<h1>{this.state.currentUser.email}</h1> 运行项目时得到的结果
TypeError: this.state.currentUser 为空
【问题讨论】:
标签: javascript reactjs firebase firebase-authentication