ant*_*rea 10 reactjs mobx mobx-react
试图基本上完成这个https://github.com/elgerlambert/redux-localstorage,它适用于Redux但是为Mobx执行.并且最好想使用sessionStorage.有一个简单的方法来实现这个最小的样板吗?
Mou*_*bar 12
解决这个问题的最简单方法是在任何可观察的属性发生变化时触发mobx"autorun".要做到这一点,你可以按照我对这个问题的回答.
我会在这里放一些示例代码来帮助您入门:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6339 次 |
| 最近记录: |