【发布时间】:2021-10-13 03:21:47
【问题描述】:
我刚刚学习了 Next.js,我在 _app.jsx 中遇到了 getInitialProps 的一个问题。
我不知道为什么会出现无限循环错误。
请告诉我为什么无限循环以及如何解决它。
const MyApp = ({ Component, pageProps }) => {
return (
<>
<Component {...pageProps} />
</>
);
};
MyApp.getInitialProps = async ({ ctx }) => {
console.log("run 1");
if (ctx.res) {
console.log("run here");
ctx.res.writeHead(302, {
Location: "/login",
});
ctx.res.end();
}
return {};
};
export default MyApp;
【问题讨论】:
-
发生无限循环是因为当您在
/login页面上时该代码也会运行。 -
谢谢,但如果我不使用 ctx.res?.writeHead(302, { Location: "/login"});在 getInitialProps 中只记录 1 次,你知道为什么吗?
标签: node.js next.js infinite-loop