首页 > 解决方案 > 在 Gatsby 中将 Context Provider 放在哪里?

问题描述

我只需要在第一次访问站点时运行一些函数(例如 Office UI Fabric React's initializeIcons())和 AXIOS 调用(例如使用 Context API 检索登录用户),然后将检索到的值存储在 React Context 中并进行它可用于整个应用程序。

Gatsby 将我的页面内容包装在Layout中,例如:

const IndexPage = () =>
<Layout>
   Body of Index Page...
</Layout>
const AnotherPage = () =>    
<Layout>
   Body of Another Page...
</Layout>

布局如下

const Layout = ({ children }) =>
<>
    <Header /> 
    <main>{children}</main>
    <Footer />
</>

我知道我不能把我的上下文放在哪里:

我想我需要一个根<app>对象来围绕我的上下文提供程序,但是用 Gatsby 实现这一目标的干净方法是什么?

我应该把上下文提供者放在哪里?

标签: javascriptreactjsaxiosgatsbyreact-context

解决方案


您定义一个根布局。与正常布局相比,没有定义“可见”页面元素,但在每个页面上都隐藏了您需要的内容,例如 ContextProviders、React Helmet、主题等:

RootLayout.jsx

export default function RootLayout({ children }) {
  return (
    <>
      <Helmet />
        <ThemeProvider theme={theme}>
          <CssBaseline />
          <ContextProvider>
            {children}
          </ContextProvider>
        </ThemeProvider>
    </>
  );
}

Gatsby 通过隐式调用此根布局gatsby-browser.jsgatsby-ssr.js并将其应用于您的每个页面。这两行相同的代码就是 Gatsby 为您处理其余部分所需的全部内容。

gatsby-browser.js

export const wrapRootElement = ({ element }) => <RootLayout>{element}</RootLayout>;

gatsby-ssr.js

export const wrapRootElement = ({ element }) => <RootLayout>{element}</RootLayout>;

概括:

  • 您将上下文提供程序放在根布局中。

参考:

  • 我在这里这里问了相关问题。我在此答案中提供的代码是您和我的问题的解决方案。如果您的整个应用程序需要此信息,那么从 React Redux 等框架改编而来的良好编码实践是使用 Context Provider 包装您的整个应用程序。
  • @Lionel T 提到的博客文章。

推荐阅读