如何在sessionStorage中保存Mobx状态 [英] How to save Mobx state in sessionStorage

查看:57
本文介绍了如何在sessionStorage中保存Mobx状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Trying to essentially accomplish this https://github.com/elgerlambert/redux-localstorage which is for Redux but do it for Mobx. And preferably would like to use sessionStorage. Is there an easy way to accomplish this with minimal boilerplate?

推荐答案

最简单的方法是在任何可观察的属性发生变化时触发mobx自动运行".为此,您可以按照我对这个问题的回答.

The easiest way to approach this would be to have a mobx "autorun" triggered whenever any observable property changes. To do that, you could follow my answer to this question.

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

I'll put some sample code here that should help you get started:

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);
  }
}

这篇关于如何在sessionStorage中保存Mobx状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆