admin管理员组文章数量:1318326
I'm working on a framework that allows developers to create extensions for a main app. Extensions can add components to different parts of the app layout, such as the sidebar or workspace, independently of one another. Here's an example of the component tree:
<app>
<Provider key="instance from Extension 1">
<Provider key="instance from Extension 2">
<Layout>
<Sidebar>
<Extension1Component1 />
<Extension2Component1 />
</Sidebar>
<Workspace>
<Extension1Component2 />
<Extension2Component2 />
</Workspace>
</Layout>
</Provider>
</Provider>
</app>
Problem:
Each extension should manage its own state and logic independently. Components from the same extension (Extension1Component1
, Extension1Component2
, etc.) need to share a context provider instance without interference from other extensions' providers.
If the logic were entirely under our control, solutions like Zustand would work perfectly to maintain a shared state. However, problems arise when an extension requires using a third-party library that mandates wrapping components with a provider (e.g., libraries like react-flow). These providers usually need to be placed around the lowest common ancestor of all components requiring shared context.
Goals:
- Share the same provider instance for components belonging to a single extension, even if they are rendered in different parts of the app.
- Prevent interference between the providers of other extensions.
Additional Question:
Would it be possible to restructure the component tree to something like this, ensuring the same Provider instance is shared between scattered components from the same extension?
<app>
<Layout>
<Sidebar>
<Provider key="instance from Extension 1">
{/* Instance is the same as the one below */}
<Extension1Component1 />
</Provider>
<Provider key="instance from Extension 2">
{/* Instance is the same as the one below */}
<Extension2Component1 />
</Provider>
</Sidebar>
<Workspace>
<Provider key="instance from Extension 1">
{/* Instance is the same as the one above */}
<Extension1Component2 />
</Provider>
<Provider key="instance from Extension 2">
{/* Instance is the same as the one above */}
<Extension2Component2 />
</Provider>
</Workspace>
</Layout>
</app>
This would enable wrapping individual components in their respective providers, but the instances must remain consistent across different parts of the app for each extension. If this approach is feasible, what would be the best way to implement it?
Any suggestions or ideas for tackling this issue would be greatly appreciated!
本文标签: reactjsHow to Share a Provider Across Isolated ComponentsStack Overflow
版权声明:本文标题:reactjs - How to Share a Provider Across Isolated Components? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742044963a2417728.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论