mobx/mobx-state-tree 中的可重用操作

Reusable actions in mobx/mobx-state-tree

我有多个 mobx 商店,我发现自己在每个商店中都有几乎相同的操作。因此,我希望能够在商店之间推广和重用它们。下面我尝试分解创建操作,希望能够将其导入多个商店,但它不起作用,因为 self 不可用。

我想从这里开始:

export const CategoriesStore = types
  .model("CategoriesStore", {
  })
  .views(self => ({
  }))
  .actions(self => {
    const collection = "categories"

    const create = flow(function* create(newItem) {
      const newItemRef = firestore.collection(collection).doc()
      const id = newItemRef.id
      self[collection].set(id, newItem)
      yield newItemRef.set(newItem)
      return id
    })
 return {
   create
 }
})

像这样,创建操作可以在其他商店中重复使用:

const create = flow(function* create(newItem, collection) {
    const newItemRef = firestore.collection(collection).doc()
    const id = newItemRef.id

    this[collection].set(id, newItem)
    yield newItemRef.set(newItem)

    return id
})

export const CategoriesStore = types
  .model("CategoriesStore", {
  })
  .views(self => ({
  }))
  .actions(self => {
    const collection = "categories"

    const _create = create.bind(self)

    return {
      _create
    }
})

关于如何实现这一点有什么想法吗?

虽然我从来没有做过那样的事情,但我一直在考虑并且觉得它应该有效。但如果没有,您可以执行以下操作:

const create = (self) => flow(function* create(newItem, collection) {
  const newItemRef = firestore.collection(collection).doc()
  const id = newItemRef.id

  self[collection].set(id, newItem)
  yield newItemRef.set(newItem)

  return id
})

export const CategoriesStore = types
.model("CategoriesStore", {
})
.views(self => ({
}))
.actions(self => {
  const collection = "categories"

  return {
    create: create(self)
  }
})

这绝对有效。