javascript - React 的 SetState 在 Firebase Auth 的 onAuthStateChanged 中导致 setState 未定义

标签 javascript reactjs firebase-authentication

//为什么这个问题不是 (How to access the correct `this` inside a callback?) 的重复:我的问题是一个特定于 react 的问题,访问者可能不会在心理上将上述链接中提出的问题与我正在努力解决的问题联系起来与。

我正在尝试存储 Firebase auth 的 onAuthStateChanged 函数返回的用户数据,并将该数据存储在状态中,以便在我的 React 应用程序中使用它。在我的应用程序中,我有以下监听器:

  componentDidMount() {

    firebase.auth().onAuthStateChanged(function(user) {

      var theUser;

      if (user) {
        console.log("user is logged in!");

        theUser = user;

        this.setState({
          session: theUser
        });
        // User is signed in.
      } else {
        // No user is signed in.
        console.log("user is not logged in!")
        theUser = null;
      }
  }
}

但我收到错误“TypeError:this.setState 不是一个函数”。我尝试将“this”绑定(bind)到 componentDidMount 无济于事。

最佳答案

正如@Jason Byrne 所说,指定谁是“这个”似乎是一个问题,您可以按照他在回答中提到的方法进行操作。

另一种现代方法是使用 ES6 arrow functions因为它们在 lexical scope 中工作,所以 this 取决于它被写入的“where”(这是你的 class):

componentDidMount() {

    firebase.auth().onAuthStateChanged(user => {

      var theUser;

      if (user) {
        console.log("user is logged in!");

        theUser = user;

        this.setState({
          session: theUser
        });
        // User is signed in.
      } else {
        // No user is signed in.
        console.log("user is not logged in!")
        theUser = null;
      }
  }
}

也可以在这里查看:How to access the correct `this` inside a callback?

关于javascript - React 的 SetState 在 Firebase Auth 的 onAuthStateChanged 中导致 setState 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53892261/

相关文章:

当我从 IE 切换到 Chrome 时,Javascript 不会重新加载页面

javascript - Lightbox2 未启动

javascript - 在 React 中创建一个保存数据的表单

reactjs - 引用错误: Cannot access 'todos' before initialization App, react js

android - 如何使用 Firebase 进行自定义身份验证?

Firebase 身份验证部分工作(仅限电子邮件)

javascript - 为什么变量没有被访问

javascript - IIFE 单例全局未定义,除非调用为 window.XYZ = IIFE()

javascript - ReactJS - 如何避免特定图像在 Lightbox 组件中最大化

Android 调试器 - Firebase 对象被混淆