我有一篇文章是一个mobx-state-tree对象,我在一个反应应用程序中使用它。
这是我树内的一个动作
setId(id: string) {
self.id = id
this.updateProduct()
},
而事件
<input
value={comp.productId}
onChange={(e) => comp.setId(e.target.value)}
/>
问题是this.updateProduct()
会在每次更改后运行,并在每次按键后进行异步调用。
我想利用mobx反应并使用类似的东西
reaction(
() => ({
id: this.id
}),
() => {
this.updateProduct()
}, {
delay: 500 // this is the key thing
})
我发现延迟在这种情况下非常有用,所以我想在树中使用它们。
在mobx-state-tree中添加反应是一个好习惯吗?如果是,使用反应的正确位置在哪里?
我可以定义反应组件内部的反应,但它们将在树外。在树外是一个好习惯吗?
您可以使用afterCreate
和beforeDestroy
动作来创建和处理反应。
例
.actions(self => {
let dispose;
const afterCreate = () => {
dispose = reaction(
() => ({
id: this.id
}),
() => {
this.updateProduct();
},
{
delay: 500
}
);
};
const beforeDestroy = dispose;
return {
afterCreate,
beforeDestroy
};
});
您也可以使用addDisposer
助手,因此如果您愿意,无需在beforeDestroy
进行手动清理。
.actions(self => {
function afterCreate() {
const dispose = reaction(
() => ({
id: this.id
}),
() => {
this.updateProduct();
},
{
delay: 500
}
);
addDisposer(self, dispose);
}
return {
afterCreate
};
});