React Firebase身份验证返回null

时间:2020-06-26 20:15:39

标签: reactjs firebase-authentication

我正在尝试检索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;

1 个答案:

答案 0 :(得分:0)

问题是,在用户在那里之前执行了render方法。

  • render方法在componentDidMount方法之前执行,因此,第一次,当前用户始终为null。在此处查看生命周期备忘单:article
  • 即使在执行onAuthStateChanged之后,也可能没有可用的用户。 Firebase建议始终在访问用户之前检查用户是否在那里,请参阅:https://twitter.com/pbesh/status/738008776805060608

因此解决方案是期望当前用户可以为null并在render方法中进行检查。示例:

{
    currentUser ? <Navbar user={currentUser} /> : <LoggedOutNavbar />
}