【问题标题】:Mobx using store in another storeMobx 在另一家商店使用商店
【发布时间】:2021-11-21 05:08:43
【问题描述】:

我有 Store AStore B 使用 types.model("Store A")... 定义的商店。 我想在另一个中使用Store B,但是如果我将Store B 添加到Store A 的props 中,则会收到错误消息"cannot add an object to a state-tree if it is already part of the same or another state-tree"

所以我的问题是,是否有可能将商店注入另一个商店?

【问题讨论】:

  • 如果可能的话,请在codesandbox.io上做一些最小的可复制示例
  • 您可以通过 UI 实现将属性或函数从 storeB 发送到 storeA。这确实是 mobx 最糟糕的事情之一
  • 我在下面添加了,它是如何工作的

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


【解决方案1】:

如果您使用 ignite-cli 创建 react-native-app,您可以像这样扩展商店:

root-store.ts:

import { IStateTreeNode, getRoot, types } from "mobx-state-tree";

export const RootStoreModel = types.model("RootStore").props({
  storeA: types.optional(StoreAModel, {}),
  storeB: types.optional(StoreBModel, {}),
})

/**
 * Adds a rootStore property to the node for a convenient
 * and strongly typed way for stores to access other stores.
 */
export const withRootStore = (self: IStateTreeNode) => ({
  views: {
    get rootStore(): RootStore {
      return getRoot<typeof RootStoreModel>(self);
    },
  },
});

如果根存储包含例如 StoreA 和 StoreB,那么您可以像这样在 StoreA 中使用 StoreB:

store-a.ts:

export const StoreA = types
  .model("StoreA")
  .extend(withRootStore)
  .actions((self) => {
    self.rootStore.storeB;
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 2016-12-16
    • 2018-06-11
    • 2015-09-04
    • 2020-08-18
    • 1970-01-01
    相关资源
    最近更新 更多