reactjs - Mobx-state-tree 在树内使用 mobx 反应 - 好习惯还是坏习惯?
问题描述
我有一篇文章是 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
};
});
推荐阅读
- cordova - Ionic http 从具有 CORS 设置的非 ssl 网站获取
- node.js - 使用(反应)node.js 的 Azure 管道和使用并发脚本的表达项目
- angular - 使用事件发射器测试可点击的 Angular 指令 - @Output() 不会引发/触发
- node.js - Discord.js 欢迎信息不显示头像
- angular - 如何将角度绑定@input与html元素值绑定
- html - 我不想更改 Bootstrap 汉堡包默认图标
- c# - EF Core 添加实体而不将其持久保存在数据库中
- arduino - 将 ESP8266 (NodeMCU) 与 Android 应用程序(MIT APP 发明者)连接,尤其是来自 gps 模块的经度和纬度
- python-3.x - 在 Odoo 中上传期间如何获取文件的本地绝对路径?
- image - QNormalDiffuseMapMaterial 和 qt 中使用的法线图像是什么时候