![](/img/trans.png)
[英]Mobx-state-tree: how to rename AnonymousModel to the store name
[英]How to share a Mobx-State-Tree store between components using React Context
我目前正在使用Mobx-State-Tree
来管理我的React应用程序中表单的所有状态。 我面临的问题是,我想按照原子设计在表单的页面级创建商店,并通过React Context将商店传递给必要的组件,但是我想避免将子组件包装在<Observer>
来自Mobx-react
<Observer>
标记,或者在我的孩子上有某种自定义包装器,它消耗了商店并将其作为道具传递给孩子。
围绕此必须有最佳实践吗? Mobx-react
文档指出:
“ 通过使用可从mobx-react
导入的MobXProviderContext
上下文,可以使用React.useContext
读取Provider
的存储。 ”
但是,我找不到任何示例或如何最好地实现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>
);
最终,我对如何避免子组件上的嵌套感兴趣? 我应该如何构造子组件? 我正在应用的情况是表单的状态管理,因此商店数据正在不断更新,因此至关重要的是,孩子要观察商店中值的任何更新。
希望这是有道理的,并且非常感谢您提供有关如何最好地实现此目标的指导!
请使用inject
将存储注入到您的组件。 您也可以建立自己的提供程序,以将商店传递给所有孩子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.