Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript mobx/mobx状态树中的可重用操作_Javascript_Mobx_Mobx State Tree - Fatal编程技术网

Javascript mobx/mobx状态树中的可重用操作

Javascript mobx/mobx状态树中的可重用操作,javascript,mobx,mobx-state-tree,Javascript,Mobx,Mobx State Tree,我有多个mobx商店,发现自己在每个商店都有几乎相同的操作。因此,我希望能够在商店之间推广和重用它们。下面我尝试了创建操作,希望能够将其导入多个商店,但由于self不可用,因此无法工作 我想从这里开始: export const CategoriesStore = types .model("CategoriesStore", { }) .views(self => ({ })) .actions(self => { const collection =

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

这肯定会奏效。

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