MobX 对象数组的深度自动运行
Deep autorun on MobX array of objects
我已经查看了 Whosebug 上的 this issue on Github and ,但我仍然不确定如何为我拥有的数据结构触发自动 运行。我从存储中获取数据作为 json 对象。
// Object keys do not change
const sampleData =
[
{
"title": "some-title",
"isActive": true,
"isCaseSensitive": false,
"hidePref": "overlay",
"tags": ["tag1", "tag2"]
},
{
"title": "all-posts",
"isActive": false,
"isCaseSensitive": true,
"hidePref": "overlay",
"tags": ["a", "b", "c"]
}
];
class Store {
@observable data;
constructor() {
this.data = getDataFromStorage();
if (this.data === null) {
this.data = sampleData;
}
}
}
const MainStore = new Store();
autorun(() => {
console.log("autorun");
sendPayloadToAnotherScript(MainStore.data);
})
每次将新对象添加到数据数组或更改对象中的任何字段值时,如何让自动运行变为运行?
实现此功能的最简单方法是使用 JSON.stringify()
递归地观察所有属性:
autorun(() => {
console.log("autorun");
// This will access all properties recursively.
const json = JSON.stringify(MainStore.data);
sendPayloadToAnotherScript(MainStore.data);
});
Mobx-State-Tree getSnapshot 也可以。尽管我现在找不到它:我读到 getSnapshot 非常快。
import { getSnapshot } from 'mobx-state-tree'
autorun(() => {
console.log("autorun");
// This will access all properties recursively.
getSnapshot(MainStore.data);
sendPayloadToAnotherScript(MainStore.data);
});
我已经查看了 Whosebug 上的 this issue on Github and
// Object keys do not change
const sampleData =
[
{
"title": "some-title",
"isActive": true,
"isCaseSensitive": false,
"hidePref": "overlay",
"tags": ["tag1", "tag2"]
},
{
"title": "all-posts",
"isActive": false,
"isCaseSensitive": true,
"hidePref": "overlay",
"tags": ["a", "b", "c"]
}
];
class Store {
@observable data;
constructor() {
this.data = getDataFromStorage();
if (this.data === null) {
this.data = sampleData;
}
}
}
const MainStore = new Store();
autorun(() => {
console.log("autorun");
sendPayloadToAnotherScript(MainStore.data);
})
每次将新对象添加到数据数组或更改对象中的任何字段值时,如何让自动运行变为运行?
实现此功能的最简单方法是使用 JSON.stringify()
递归地观察所有属性:
autorun(() => {
console.log("autorun");
// This will access all properties recursively.
const json = JSON.stringify(MainStore.data);
sendPayloadToAnotherScript(MainStore.data);
});
Mobx-State-Tree getSnapshot 也可以。尽管我现在找不到它:我读到 getSnapshot 非常快。
import { getSnapshot } from 'mobx-state-tree'
autorun(() => {
console.log("autorun");
// This will access all properties recursively.
getSnapshot(MainStore.data);
sendPayloadToAnotherScript(MainStore.data);
});