我想将我的mobx状态存储在浏览器localStorage中,所以,如果我使用这种方法https://stackoverflow.com/a/40326316我用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];
});
...
}
但是我认为这是反模式。
如果您有一个类,并且“原始” json数据,我正在做的是在构造函数中接受原始数据,然后更新该类的属性。
例如,我的原始数据如下:
{
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);
这种方法中的cool就是嵌套处理,每个“级别”都处理其部分。