【问题标题】:How to share a Mobx-State-Tree store between components using React Context如何使用 React Context 在组件之间共享 Mobx-State-Tree 存储
【发布时间】:2019-06-26 21:40:08
【问题描述】:

我目前正在使用Mobx-State-Tree 来管理我的 React 应用程序中表单的所有状态。我面临的问题是我想在表单的原子设计之后在页面级别创建商店,并通过 React Context 将商店传递给必要的组件,但我想避免将我的子组件包装在 @ 987654323@ 来自Mobx-react 的标签,或者在我的孩子身上使用某种自定义包装器来消费商店并将其作为道具传递给孩子。

必须有一个最佳实践来解决这个问题? Mobx-react 文档指出:

"可以使用React.useContext 读取Provider 提供的商店,通过使用可以从mobx-react 导入的MobXProviderContext 上下文。"

但是我找不到任何示例或解释如何最好地实施 MobXProviderContext ?我目前的设置如下(为了演示情况而进行了极大的简化):

import { types } from "mobx-state-tree";

const ExampleContext = React.createContext("default");

const exampleStore = types.model({ prop: types.optional(types.string, "") }).create();

const ChildComponent = () => (
  <ExampleContext.Consumer>
    {example => <Observer>{() => <div>{example.prop}</div>}</Observer>}
  </ExampleContext.Consumer>
);

const ParentComponent = () => (
<ExampleContext.Provider value={exampleStore}>
   <ChildComponent />
</ExampleContext.Provider>
);

最终我对如何避免子组件上的嵌套感兴趣?我应该如何构建子组件?我将其应用于表单的状态管理,因此存储数据不断更新,因此孩子观察存储中值的任何更新至关重要。

希望这是有道理的,并且非常感谢有关如何最好地解决此问题的任何指导!

【问题讨论】:

  • 看看这是否能让你更接近解决方案:stackoverflow.com/questions/54393475/…
  • 也不确定为什么要避免使用 Observer 包装器。它只是将组件订阅到可观察对象和可计算对象。这不是你想要的吗?

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


【解决方案1】:

请使用inject 将 store 注入您的组件。您也可以建立自己的提供者,以便将商店传递给所有孩子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 2015-08-25
    相关资源
    最近更新 更多