【问题标题】:Reusable actions in mobx/mobx-state-treemobx/mobx-state-tree 中的可重用操作
【发布时间】:2019-11-26 05:38:44
【问题描述】:

我有多个 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
    }
})

关于如何实现这一点的任何想法?

【问题讨论】:

  • 你是说,你这里的东西行不通吗?
  • 是的,现在在问题中澄清了这一点。感谢您的帮助,效果很好!

标签: javascript mobx mobx-state-tree


【解决方案1】:

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

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

这肯定行得通。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    相关资源
    最近更新 更多