2

我有一个对象,它具有一些持久保存在 cookie 中的可观察属性:

class MyClass {
  @observable attribute = Cookies.get("attribute");

  @action updateAttribute(newValue) {
    this.attribute = newValue;
    Cookies.set("attribute", newValue);
  }
}

var obj = new MyClass();

这显然不理想,因为现在我将数据保存在两个地方(属性和 cookie)。理想情况下,我想做这样的事情:

class MyClass {
  @computed get attribute() {
    return Cookies.get("attribute");
  }

  @action updateAttribute(newValue) {
    Cookies.set("attribute", newValue);
    // Somehow mark the computed property `this.attribute` as dirty.
  }
}

像这样的解决方案可能有效:

class MyClass {
  @observable _version = 0;

  @computed get attribute() {
    // Read `this._version` to create the dependency.
    this._version;
    return Cookies.get("attribute");
  }

  @action updateAttribute(newValue) {
    Cookies.set("attribute", newValue);
    this._version++;
  }
}

有没有更好的方法来实现这一目标?

4

1 回答 1

2

我认为您的解决方案实际上非常好。另一种解决方案是在启动时只“读取”一次 cookie,然后使用 autorun 来存储 cookie:

class MyClass {
  @observable attribute = Cookie.get("attribute")

  constructor() {
    autorun(() => Cookie.set("attribute", this.attribute))
  }
}    
于 2016-07-08T07:11:59.490 回答