0

这是我的 Mobx 商店:

import { observable } from 'mobx';
import fb from '../Firebase';
import User from '../User';

export default class Profile {

  @observable profile = {};
  @observable uid = null;

  /**
   * @return {void}
   */
  constructor(user) {
    this.user = user;
    fb.firebase.auth().onAuthStateChanged(() => {
      this.uid = user.currentUser.uid;
      fb.profiles.child(this.uid).on('value', (snapshot) => {

        // Doesn't matter what I will do here with this.profile...
        this.profile = snapshot.val();
        
      });
    });
  }
}

尝试使用观察者的配置文件可观察属性。但由于某种原因,我无法从中获得更新的状态。

如果我在“fb.profiles.child”之前更新配置文件而不是从回调中更新,那么它将起作用。

任何人都知道为什么会这样?我想可能是因为它已经安装到观察者或类似的东西......

4

2 回答 2

0

所以用这个问题解决我的问题是不可能的,最重要的部分丢失了。

组件中有一个componentWillMount。删除后解决了我的问题。

于 2017-05-23T22:09:23.273 回答
0

为了正确更新对象,您应该使用observable( https://mobx.js.org/refguide/observable.html ) 并Object.assign定义profile.

以下是几个(未经测试的)示例:

@observable profile = observable({});
.
.
.
this.profile = Object.assign({}, this.profile, snapshot.val());

如果Object.assign没有触发更新,那么你需要使用extendObservable()https://mobx.js.org/refguide/extend-observable.html):

@observable profile = observable({});
.
.
.
extendObservable(profile, snapshot.val());

另一种选择是使用observable.maphttps://mobx.js.org/refguide/map.html)更复杂的结构:

@observable profile = observable.map({ profileData: {} });
.
.
.
const currentProfile = this.profile.get('profileData'); 
this.profile.set('profileData', Object.assign({}, currentProfile, snapshot.val()));
于 2017-05-23T04:43:12.570 回答