我正在尝试检索Firebase Auth对象的属性。当我在控制台中打印Auth对象时,我可以访问“ displayName”属性,但是当我将Auth对象传递到我的组件中时,我总是收到错误消息“无法读取null的属性'displayName'”。这是下面的代码:
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;
答案 0 :(得分:0)
问题是,在用户在那里之前执行了render方法。
因此解决方案是期望当前用户可以为null并在render方法中进行检查。示例:
{
currentUser ? <Navbar user={currentUser} /> : <LoggedOutNavbar />
}