【问题标题】:Get parent data from a child从孩子那里获取父母数据
【发布时间】:2019-02-21 23:02:38
【问题描述】:

什么方法更好?我认为比第一种方式更好。在孩子中导入父母对我来说看起来很奇怪,但也许我错了。

根存储:

export const RootStore = types
  .model('RootStore', {
    store1: types.optional(Store1, {}),
    store2: types.optional(Store2, {}),
    store3: types.optional(Store3, {}),
    store3: types.optional(Store4, {}),
    name: 'name'
  })

export const rootStore = RootStore.create()

第一种方式:

export const Store1 = types
  .model('Store1', {
    some: ''
  })
  .views(self => ({
    get rootStore() {
      return getParent(self)
    },
    get name() {
      return self.rootStore.name
    }
  }))

第二种方式:


import { rootStore } from './rootStore'

export const Store1 = types
  .model('Store1', {
    some: ''
  })
  .views(self => ({
    get name() {
      return rootStore.name
    }
  }))

【问题讨论】:

    标签: mobx-state-tree


    【解决方案1】:

    这个问题的所有答案都可能是固执己见..

    如果你要这样做,我认为第一种方法更好。仅仅因为这意味着孩子不需要知道任何关于它的父母的事情,除了它公开了一个name 属性。

    话虽如此,我真的不喜欢这两种方法。

    无论您使用getParent 还是闭包,这都会促进两个模型的耦合。这会导致模块化程度降低和测试难度加大,因为每个 Store1 都必须是 RootStore 的子代才能正常运行。

    我认为更好的方法是消除孩子->父母之间的依赖关系。但是,如果您有目的地使用 MST 提供的树形结构,我的建议在理论上可能比实践要好。

    删除依赖的最简单方法是让Store1 的操作/视图的调用者将所需的任何数据作为参数传递。再一次,这在实践中并不总是有意义的。

    【讨论】:

      【解决方案2】:

      如果您只需要访问树中的根节点,那么有一个专门针对这种情况的专用帮助函数 - getRoot(self)

      给定模型树中的一个对象,返回该树的根对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-31
        • 1970-01-01
        • 2019-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多