当我们在next.js中有两个单独的布局时,如何在布局中使用上下文



我在NextJS中使用了两个独立的布局。当我这样调用上下文时,我可以访问布局的子级中的值,但我不能访问布局,并且上下文返回undefined。

这是我的背景:

import React from "react";
export const AuthContext = React.createContext();

_app.js:

function MyApp({Component, pageProps}) {
const getLayout = Component.getLayout || ((page) => page)
const [state, setState] = useState('')
return getLayout(
<AuthContext.Provider value={{
state,
setState
}}>
<Component {...pageProps} />
</AuthContext.Provider>
)
}
export default MyApp

我在每个页面中添加此代码以使用布局一或布局二

index.getLayout = function getLayout(page) {
return (
<Layout1>
{page}
</Layout1>
)
}

i更改app.js:

return (
<AuthContext.Provider value={{
auth,
dispatch
}}>
{getLayout(<Component {...pageProps} />)}
</AuthContext.Provider>
)

因为布局不在上下文中

最新更新