javascript - 在 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 />
</>
我知道我不能把我的上下文放在哪里:
围绕页面(或者每次点击页面时都会执行,并且对其他页面不可用):
const IndexPage = () => <MyContextProvider> <Layout> Context Available here </Layout> </MyContextProvider>
const AnotherPage = () => <Layout> Context NOT available here </Layout>
在布局中(或者每次都会执行):
const Layout = ({ children }) => <MyContextProvider> <Header /> <main>{children}</main> <Footer /> </MyContextProvider>
我想我需要一个根<app>
对象来围绕我的上下文提供程序,但是用 Gatsby 实现这一目标的干净方法是什么?
我应该把上下文提供者放在哪里?
解决方案
您定义一个根布局。与正常布局相比,没有定义“可见”页面元素,但在每个页面上都隐藏了您需要的内容,例如 ContextProviders、React Helmet、主题等:
RootLayout.jsx
:
export default function RootLayout({ children }) {
return (
<>
<Helmet />
<ThemeProvider theme={theme}>
<CssBaseline />
<ContextProvider>
{children}
</ContextProvider>
</ThemeProvider>
</>
);
}
Gatsby 通过隐式调用此根布局gatsby-browser.js
,gatsby-ssr.js
并将其应用于您的每个页面。这两行相同的代码就是 Gatsby 为您处理其余部分所需的全部内容。
gatsby-browser.js
:
export const wrapRootElement = ({ element }) => <RootLayout>{element}</RootLayout>;
gatsby-ssr.js
:
export const wrapRootElement = ({ element }) => <RootLayout>{element}</RootLayout>;
概括:
- 您将上下文提供程序放在根布局中。
参考: