小编典典

如何在sessionStorage中保存Mobx状态

reactjs

试图从根本上实现此https://github.com/elgerlambert/redux-
localstorage,它适用于Redux,但适用于Mobx。并且最好是想使用sessionStorage。有没有一种简单的方法可以以最少的样板实现这一目标?


阅读 428

收藏
2020-07-22

共1个答案

小编典典

解决此问题的最简单方法是,只要任何可观察的属性发生变化,就会触发mobx“自动运行”。为此,您可以按照我对这个问题的回答。

我将在此处放置一些示例代码,以帮助您入门:

function autoSave(store, save) {
  let firstRun = true;
  mobx.autorun(() => {
    // This code will run every time any observable property
    // on the store is updated.
    const json = JSON.stringify(mobx.toJS(store));
    if (!firstRun) {
      save(json);
    }
    firstRun = false;
  });
}

class MyStore {
  @mobx.observable prop1 = 999;
  @mobx.observable prop2 = [100, 200];

  constructor() {
    this.load();
    autoSave(this, this.save.bind(this));
  }

  load() {
    if (/* there is data in sessionStorage */) {
      const data = /* somehow get the data from sessionStorage or anywhere else */;
      mobx.extendObservable(this, data);
    }
  }

  save(json) {
    // Now you can do whatever you want with `json`.
    // e.g. save it to session storage.
    alert(json);
  }
}
2020-07-22