太多 React Context 提供者 [英] Too many React Context providers

查看:25
本文介绍了太多 React Context 提供者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚在这里做出反应,并试图将我的头脑围绕在新的 Context API 上(我还没有研究过 Redux 等).

New to react here and trying to wrap my head round the new Context API (I haven't looked into Redux etc. yet).

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

Seems I can do much of what I need to do, but I'm going to end up with lots and lots of providers, all needing a tag to wrap my main app.

我将有一个用于身份验证的提供程序,一个用于主题,一个用于聊天消息(vis Pusher.com)等.另外,使用 React Router 是另一个包装元素.

I'm going to have a provider for Auth, one for theming, one for chat messages (vis Pusher.com) etc. Also using React Router is another wrapper element.

我是否将不得不以这个(以及更多)告终....

Am I going to have to end up with this (and many more)....

<BrowserRouter>
    <AuthProvider>
        <ThemeProvider>
            <ChatProvider>
                <App />
            </ChatProvider>
        </ThemeProvider>
    </AuthProvider>
</BrowserRouter>

或者有更好的方法吗?

推荐答案

如果您想要一种无需任何第三方库即可组合 Provider 的解决方案,这里有一个带有 Typescript 注释的解决方案:

If you want a solution for composing Providers without any third-party libraries, here's one with Typescript annotations:

// 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,当然可以删除注释.

You can of course remove the annotations if you don't use Typescript.

这篇关于太多 React Context 提供者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆