如何从 json 加载 mobx 状态?

How to load mobx state from json?

我想在浏览器 localStorage 中存储我的 mobx 状态,所以,如果我使用这种方法
我用 toJS 保存商店,但不知道如何应用它。使用 extendObservable 我得到以下错误 Error: [mobx] 'extendObservable' can only be used to introduce new properties. Use 'set' or 'decorate' instead
提前致谢。

我的做法是:

class MyStore {
...
  public async load() {
      const cached = await browser.storage.local.get("cache");
        const data = JSON.parse(cached["cached"]);
        Object.keys(data).forEach(x => {
          (this as any)[x] = (data as any)[x];
       });
...
}

但我认为这是反模式。

如果您有 class 和 "raw" json 数据,我正在做的是在构造函数中接受原始数据,然后更新 class属性。

例如,我的原始数据是这样的:

{
  users: [
    { id: 1, firstName: 'foo', lastName: 'bar', customer: { id: 1, name: 'bla' } },
    { id: 2, firstName: 'foo2', lastName: 'bar2', customer: { id: 2, name: 'customer' } },
  ];
}
class User {
  id;
  @observable firstName;
  @observable lastName;
  customer;

  constructor(rawUser) {
    this.id = rawUser.id;
    this.firstName = rawUser.firstName;
    this.lastName = rawUser.lastName;
    this.customer = new Customer(rawUser.customer);
  }
}
class UsersStore {
  @observable users = [];

  constructor(rawUsers) {
    this.users = rawUsers.map(rawUser => new User(rawUser));
  }
}

然后当我恢复数据时我只使用

const usersStore = new UsersStore(rawData.users);

这种方法中的嵌套处理,每个"level"处理它的部分。

您确定 extendObservable 不起作用吗? 我在我的代码中使用了类似的东西。

class MyStore {
  async load() {
      const cached = await browser.storage.local.get("cache");
      mobx.extendObservable(this, cached);
  }
}

编辑:

这似乎不起作用,您需要访问 extendObservable 之后的属性才能重新加载它们,您可以使用自动运行,但只需使用其他方法。

我已经基于一个简单的 forEach 实现了加载功能; 请尝试以下操作。

load = async () => {
    const { cache } = await JSON.parse(localStorage.getItem("cache"));

    Object.keys(cache).forEach(key => {
      this[key] = cache[key];
    });
  };

代码沙箱 https://codesandbox.io/s/late-snow-xppx0?ontsize=14&hidenavigation=1&theme=dark