【问题标题】:Can't rewrite observable variable in mobx store无法重写 mobx 商店中的可观察变量
【发布时间】:2017-05-22 22:13:01
【问题描述】:

这是我的 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”之前更新配置文件而不是从回调中更新,那么它将有效。

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

【问题讨论】:

    标签: firebase react-native firebase-realtime-database mobx mobx-react


    【解决方案1】:

    为了正确更新对象,您应该使用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.map (https://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()));
    

    【讨论】:

    • 仍然没有运气。如果我使用从组件调用的简单方法将配置文件从商店打印到控制台,则配置文件日期将是控制台中的更新数据,但组件中的对象为空。
    • 你有没有得到任何地方?
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多