首页 > 解决方案 > 在 Next.js 的 getInitialProps 中重定向时出现无限循环

问题描述

我刚刚学习了 Next.js,但我对getInitialPropsin有一个问题_app.jsx。我不知道为什么会出现无限循环错误。请告诉我为什么无限循环以及如何解决它。

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;

标签: node.jsnext.jsinfinite-loop

解决方案


发生无限循环是因为当您在/login页面上时也会发生重定向。为防止出现这种情况,请确保您在该页面上时不会发生重定向。

MyApp.getInitialProps = async ({ ctx }) => {
    if (ctx.res && ctx.asPath !== "/login") {
        ctx.res.writeHead(302, {
            Location: "/login",
        });
        ctx.res.end();
     }
     return {};
};

推荐阅读