Reactjs React firebase身份验证返回null
我正在尝试检索firebase Auth对象的属性。当我在控制台中打印Auth对象时,我能够访问“displayName”属性,但当我将Auth对象传递到我的组件中时,我不断收到错误“无法读取null的属性'displayName'。代码如下:Reactjs React firebase身份验证返回null,reactjs,firebase-authentication,Reactjs,Firebase Authentication,我正在尝试检索firebase Auth对象的属性。当我在控制台中打印Auth对象时,我能够访问“displayName”属性,但当我将Auth对象传递到我的组件中时,我不断收到错误“无法读取null的属性'displayName'。代码如下: class App extends React.Component { constructor() { super(); this.state = { currentUser: null, }; } u
class App extends React.Component {
constructor() {
super();
this.state = {
currentUser: null,
};
}
unsubscribeFromAuth = null;
componentDidMount() {
this.unsubscribeFromAuth = auth.onAuthStateChanged((user) => {
this.setState({ currentUser: user });
console.log(user.displayName); // I am able to access the property here
});
}
componentWillUnmount() {
this.unsubscribeFromAuth();
}
render() {
const { currentUser } = this.state;
console.log(currentUser.displayName); // I am unable to access it here
return (
<div className="App">
<Navbar currentUser={currentUser} />
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/login" component={LoginPage} />
<Route path="/signup" component={SignUpPage} />
<Route path="/shop" component={ShopPage} />
</Switch>
</div>
);
}
}
export default App;
类应用程序扩展了React.Component{
构造函数(){
超级();
此.state={
当前用户:null,
};
}
unsubscribeFromAuth=null;
componentDidMount(){
this.unsubscribeFromAuth=auth.onAuthStateChanged((用户)=>{
this.setState({currentUser:user});
console.log(user.displayName);//我可以在这里访问属性
});
}
组件将卸载(){
这是。unsubscribeFromAuth();
}
render(){
const{currentUser}=this.state;
console.log(currentUser.displayName);//我无法在此处访问它
返回(
);
}
}
导出默认应用程序;
问题在于,渲染方法在用户到达之前执行
- render方法在componentDidMount方法之前执行,因此第一次,当前用户始终为null。请参见此处的生命周期备忘表:
- 即使在执行onAuthStateChanged之后,也可能没有可用的用户。Firebase建议始终检查用户是否在那里,在访问之前,请参阅:
{
当前用户?:
}
我也面临同样的问题。@Amiteshmanitiwari与组件生命周期有关。将currentUser放入三元运算符{currentUser?:}