【问题标题】:How to modify a property in a Javascript class from within a method of that class?如何从该类的方法中修改 Javascript 类中的属性?
【发布时间】:2020-05-03 09:56:19
【问题描述】:

我正在创建一个 React 应用程序,其中有一个名为 FirebaseManager 的类。使用 Google 登录后,我们从 Firebase 中检索一个包含用户所需的所有信息的对象。我想将此信息存储在 User 类的对象中,以便在 UI 中本地提供它。为此,我在FirebaseManager 中创建了一个属性currentUser,在其中我初始化了一个User 的空对象,然后使用updateUser 方法对其进行更新。这是他们的代码:

// Current logged in user
  currentUser = new User();

  // Update user
  updateUser(user, data) {
    user.name = data.user.displayName;
    user.email = data.user.email;
    user.picture = data.user.photoURL;
    user.uid = data.user.uid;
    console.log("User inside updateUser method: ", user, "Data: ", data)
  };

现在,我在使用 Google 登录 Firebase 后立即致电 updateUser。我用responseGoogle的方法做到这一点:


// Logs in with Google
  responseGoogle = googleUser => {
    const unsubscribe = firebase.auth().onAuthStateChanged(firebaseUser => {
      unsubscribe();
      if (!this.isGoogleUserEqual(googleUser, firebaseUser)) {
        // Build Firebase credential with the Google ID token.
        const credential = this.googleProvider.credential(googleUser.tokenId);
        // Sign in with credential from the Google user.
        firebase
          .auth()
          .signInWithCredential(credential)
          .then(data => {
            // We populate the currentUser object
            this.updateUser(this.currentUser, data)
            console.log("Current user from promise: ", this.currentUser);
          })
          .catch(error => {
            console.log(error);
          });
      } else {
        console.log("User already signed-in Firebase.");
      }
    });
  };

在.then 承诺中,currentUser 属性被修改,但每当我尝试从另一个文件导入它时,它是空的,并且它的新值尚未填充。我将其导入另一个文件的方法是导出FirebaseManager 类的对象:

let firebaseManager = new FirebaseManager();

export default firebaseManager;

然后我只需在我需要的文件中导入firebaseManager 并尝试访问属性currentUser,但firebaseManager.currentUser 总是返回类User 的空对象。

总而言之,总而言之,我们想要的是能够将来自 Firebase 的用户信息存储在 User 对象中,并能够将其导出到应用中的其他模块。

谢谢

【问题讨论】:

    标签: javascript reactjs firebase oop


    【解决方案1】:

    事实证明,每当我调用 firebaseManager 对象时,都会创建该类的一个新对象,因此,即使我在一个对象中更改了属性 currentUser,此更改也不会在其余部分中复制对象。

    相反,我所做的是:

    1. 重构 FirebaseManager 类并将其转换为多个对象。
    2. 使用此firebase state listener 填充User 类的对象。
    3. 我是从我的应用程序的最通用组件中执行此操作的:App。我将活动用户存储在其状态中,并将其传递给任何需要它的子组件。

    附带说明,此功能可以通过 Redux 进行改进,我们可能会在未来实现此功能。

    【讨论】:

      猜你喜欢
      • 2019-05-30
      • 1970-01-01
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多