Mobx-state-tree 在树内使用 mobx 反应 - 好的还是坏的做法?

Mobx-state-tree use mobx reactions inside the tree - Good or Bad practice?

我有一篇文章是一个 mobx-state-tree 对象,我正在 React 应用程序中使用它。

这是我的树中的一个动作

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 中添加反应是一个好习惯吗?如果是,使用反应的正确位置在哪里?

我可以在反应组件内定义反应,但它们将在树之外。在树外面是个好习惯吗?

您可以使用 afterCreatebeforeDestroy 操作来创建和处理反应。

例子

.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
  };
});