etu*_*dor 2 reactjs mobx mobx-react mobx-state-tree
我有一篇文章是 mobx-state-tree 对象,我在 React 应用程序中使用它。
这是我的树内的一个动作
setId(id: string) {
self.id = id
this.updateProduct()
},
Run Code Online (Sandbox Code Playgroud)
还有活动
<input
value={comp.productId}
onChange={(e) => comp.setId(e.target.value)}
/>
Run Code Online (Sandbox Code Playgroud)
问题是this.updateProduct()每次更改都会运行,并在每次按键后进行异步调用。
我想利用 mobx 反应并使用类似的东西
reaction(
() => ({
id: this.id
}),
() => {
this.updateProduct()
}, {
delay: 500 // this is the key thing
})
Run Code Online (Sandbox Code Playgroud)
我发现延迟在这种情况下非常有用,所以我想在树内使用它们。
在 mobx 状态树中添加反应是一个好习惯吗?如果是,使用反应的正确位置在哪里?
我可以在反应组件内定义反应,但它将在树之外。在树外面是个好习惯吗?
您可以使用afterCreate和beforeDestroy操作来创建和处理反应。
例子
.actions(self => {
let dispose;
const afterCreate = () => {
dispose = reaction(
() => ({
id: this.id
}),
() => {
this.updateProduct();
},
{
delay: 500
}
);
};
const beforeDestroy = dispose;
return {
afterCreate,
beforeDestroy
};
});
Run Code Online (Sandbox Code Playgroud)
如果您愿意,您还可以使用addDisposer帮助程序,因此无需手动清理beforeDestroy。
.actions(self => {
function afterCreate() {
const dispose = reaction(
() => ({
id: this.id
}),
() => {
this.updateProduct();
},
{
delay: 500
}
);
addDisposer(self, dispose);
}
return {
afterCreate
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1036 次 |
| 最近记录: |