React Context提供者过多

在这里做出反应并尝试将新的Context API包裹住(我还没有研究Redux等)。

似乎我可以做很多我需要做的事情,但是最终我将得到很多提供程序,所有提供程序都需要一个标签来包装我的主应用程序。

我将要为Auth提供一个提供程序,一个为主题提供程序,一个为聊天消息提供程序(通过Pusher.com访问),等等。另外使用React

Router的是另一个包装元素。

我要结束这个(还有更多)吗?

<BrowserRouter>

<AuthProvider>

<ThemeProvider>

<ChatProvider>

<App />

</ChatProvider>

</ThemeProvider>

</AuthProvider>

</BrowserRouter>

或者,还有更好的方法?

回答:

使用@ rista404的答案-

如果您想要一种无需任何第三方库即可组成Provider的解决方案,请使用带Typescript注释的解决方案:

// Compose.tsx

interface Props {

components: Array<React.JSXElementConstructor<React.PropsWithChildren<any>>>

children: React.ReactNode

}

export default function Compose(props: Props) {

const { components = [], children } = props

return (

<>

{components.reduceRight((acc, Comp) => {

return <Comp>{acc}</Comp>

}, children)}

</>

)

}

用法:

<Compose components={[BrowserRouter, AuthProvider, ThemeProvider, ChatProvider]}>

<App />

</Compose>

如果您不使用Typescript,当然可以删除注释。

react-context-composer已过时。

感谢@ AO17,以便ping。


免责声明: 我从未使用过它 ,只是进行了研究。

FormidableLabs(他们为许多OSS项目做出了贡献)有一个名为react-context-

composer的项目

看来可以解决您的问题。

React正在提出一个新的Context API。API鼓励撰写。当您的组件将呈现多个Context

Providers和Consumers时,此实用程序组件可帮助保持代码干净。

以上是 React Context提供者过多 的全部内容, 来源链接: utcz.com/qa/399010.html

回到顶部