微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Mobx颤振中观察其他类别的场变量?

如何解决如何在Mobx颤振中观察其他类别的场变量?

我正在使用颤抖的Mobx进行状态管理。 我有一堂简单的课:-

class A {
  int x;
  A(this.x);
 }

我如何观察x是否在另一个Mobx存储中的类内更改:-

class MyStore extends _MyStore  with _$MyStore  {
  Subs(A a) : super(a);
}

abstract class _MyStore  with Store {
  @observable
  A a;
  _Subs(this.a)
}

我希望MyStore观察斧头。

有可能吗,如果可以,怎么办?

解决方法

我不确定这是否有用,因为它是Javascript / Typescript,但这就是我要做的:

class Foo {
  @observable name = 'foo'
}

class Bar {
  foo: Foo

  constructor(instanceOfFoo) {
    this.foo = instanceOfFoo

    autorun(() => {
      // Logs foo name when it changes
      console.log(this.foo.name)
    })

    reaction(
      () => this.foo.name,() => {
        // Logs foo name when it changes
        console.log(this.foo.name)
      }
    )
  }

  @observable
  name = 'bar'

  @computed
  get fooNamePlusBarName {
    // recomputes automatically whenever foo or bar name changes
    return this.foo.name + this.name
  }
}

基本上,您将Foo实例传递给Bar构造函数(或在适合的情况下仅使用导入的单例),那么您有3个选择:computedreactionautorun

,

前几天,我用颤抖mobx ^1.2.1+3(飞镖)遇到了相同的问题, flutter_mobx ^1.1.0+2

我想到的第一件事就是用x属性为有问题的字段注解,即@observable。但这在商店类之外似乎并不有效。 因此,您必须使用Observable类来观察该字段。

要使其正常工作,您的代码应如下所示:

class A {
  //replace with less verbose "var"
  Observable<int> x = Observable(0);
  A(this.x);
 }

class MyStore extends _MyStore  with _$MyStore  {
  Subs(A a) : super(a);
}

abstract class _MyStore  with Store {
  
  A a;
  _Subs(this.a)
  
  //Will be calculated whenever a change to a.x is observed.
  @computed
  int get xSquare => a.x.value * a.x.value;
}

如您所见,我从a中删除了observable属性,因为如果您想对商店中对a.x的更改做出反应,就不必观察它。您可能已经注意到,必须使用.value访问observable的值。

那应该得出结论,您如何观察商店内部商店内部某个类的字段。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。