javascript-等待来自另一个mobx存储的异步数据

我有2个商店:UserStore和TodoStore.
为了获取待办事项,我需要知道已登录用户的ID.

那是我的UserStore的一部分

export default class UserStore {
  @observable currentUser = null;
  @observable loading = false;

  constructor() {
    this.subscribe();
  }

  @action subscribe = () => {
    this.loading = true;
    firebase.auth().onAuthStateChanged((user) => {
      if(user) {
        this.setCurrentUser(user);
      } else {
        this.unsetCurrentUser();
      }
      this.loading = false;
    })
  }
}

这是我的TodoStore的构造函数

constructor(users) {
    this.users = users;

    console.log(this.users.currentUser) //null

    this.storageRef = firebase.storage().ref('files/todos');
    this.todosRef = firebase.database().ref(`todos/${this.users.currentUser.uid}`);
    this.filesRef = firebase.database().ref(`files/${this.users.currentUser.uid}/todos`);

    this.logger();
  }

这里的问题是我收到错误消息,因为在调用此函数时currentUser仍然为null.

这就是我合并商店的方式:

const routing = new RouterStore();
const ui = new UiStore();
const users = new UserStore(ui);
const todos = new TodoStore(users);

const stores = {
  routing,
  ui,
  users,
  todos,
}

我究竟做错了什么?我怎么知道currentUser Observable何时可用?

解决方法:

我认为最简单的解决方案是在用户存储中保存对Firebase Auth Promise的引用,并在解决后在TodoStore中使用currentUser:

// UserStore.js
export default class UserStore {
  @observable currentUser = null;
  @observable loading = false;
  authPromise = null;

  constructor() {
    this.subscribe();
  }

  @action subscribe = () => {
    this.loading = true;
    this.authPromise = firebase.auth().onAuthStateChanged((user) => {
      if(user) {
        this.currentUser = user;
      } else {
        this.currentUser = null;
      }
      this.loading = false;
    })
  }
}

// TodoStore.js
export default class TodoStore {
  constructor(userStore) {
    this.userStore = userStore;
    userStore.authPromise.then(() => {
      const uid = userStore.currentUser.uid;
      this.storageRef = firebase.storage().ref('files/todos');
      this.todosRef = firebase.database().ref(`todos/${uid}`);
      this.filesRef = firebase.database().ref(`files/${uid}/todos`);
      this.logger();
    });
  }
}
上一篇:javascript – 没有React可以使用MobX吗?


下一篇:javascript – 解决Mobx中的承诺?