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

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

标签: reactjsmobxmobx-reactmobx-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
  };
});

推荐阅读