Mobx状态树在树内使用Mobx反应-好的还是不好的做法?

时间:2019-03-14 13:53:02

标签: reactjs mobx mobx-react mobx-state-tree

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

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

1 个答案:

答案 0 :(得分:1)

您可以使用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
  };
});
相关问题