[英]How to Server Side load data in App.js next.js
I have a layout component that is loaded once on App.jsx and stays the same throughout the session, but since the page is SSRed it loads first, then the layout displays after a second, is there a way to get the layout data along with the page without having to add it to every page ?我有一个布局组件,它在 App.jsx 上加载一次,并且在整个 session 中保持不变,但是由于页面是 SSRed 它首先加载,然后布局在一秒钟后显示,有没有办法获取布局数据以及无需将其添加到每个页面的页面?
function MyApp({ Component, pageProps: { session, ...pageProps } }) {
const abortController = new AbortController();
const signal = abortController.signal;
const [content, setContent] = useState();
const router = useRouter();
console.log("url", router);
useEffect(() => {
const fetchUIContent = async () => {
let data;
let responseStatus;
try {
data = await axios.get("/api/layout", {
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
signal: signal,
});
responseStatus = data.status;
} catch (error) {
if (error.name === "AbortError") return;
console.log("Error message:", error.message);
} finally {
if (responseStatus == 200) {
setContent(await data.data);
} else {
console.log("Oops error", responseStatus, "occurred");
}
}
};
fetchUIContent();
return () => {
abortController.abort();
};
}, []);
return (
<Provider store={store}>
<SessionProvider session={session} /*option={{clientMaxAge: 10}}*/>
<ConfigProvider direction="ltr">
<HeadersComponent>
<Layout content={content}>
<Component {...pageProps} />
</Layout>
</HeadersComponent>
</ConfigProvider>
</SessionProvider>
</Provider>
);
}
I thought of using redux to get the layout data, but that would still need to make changes on each page and it is a pretty large project.我想过使用 redux 来获取布局数据,但这仍然需要在每个页面上进行更改,这是一个相当大的项目。
Fixed by https://github.com/vercel/next.js/discussions/39414 For Future readers, this is how to add extra props for use in MyApp由https 修复:对于未来的读者,这是如何添加额外的道具以在 MyApp 中使用
//to consume foo
function MyApp({ Component, pageProps, foo }) { //if you have {Component, pageProps: { session, ...pageProps }, foo} make sure foo is outside the pageProps destructure
return (
<MyFooConsumer foo={foo}>
<Component {...pageProps} />
</MyFooConsumer>
)
}
//to send foo
MyApp.getInitialProps = async (appContext) => {
// calls page's `getInitialProps` and fills `appProps.pageProps`
const appProps = await App.getInitialProps(appContext);
return { ...appProps, foo: 'bar' }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.