试图从根本上实现这一点https://github.com/elgerlambert/redux-localstorage https://github.com/elgerlambert/redux-localstorage这是针对 Redux 的,但也适用于 Mobx。并且最好想使用sessionStorage。有没有一种简单的方法可以用最少的样板来实现这一点?
解决这个问题的最简单方法是每当任何可观察到的属性发生变化时都会触发 mobx“自动运行”。为此,您可以按照我对这个问题的回答 https://stackoverflow.com/a/39992005/688405.
我将在此处放置一些示例代码来帮助您入门:
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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)