如何为 next.js 中的每个页面使用 getServerSideProps?

ang*_*elo 3 cookies next.js getserversideprops

我已经设置了一个带有 nookies 的 cookie,它存储用户选择的所有产品的值。我想使用 getServerSideProps 在服务器端获取 cookie 并将值作为道具传递。我必须在所有页面上显示 cookie 的值。

当我在 _app.js 中尝试 getServerSideProps 时。它没有工作,甚至没有运行代码。

有什么办法吗?

cod*_*ode 38

到目前为止,还没有内置的方法可以做到这一点,所以我采取了以下措施。

首先,我创建了一个文件,其中包含getServerSideProps我想要在每个页面上运行的函数:

// lib/serverProps.js
export default async function getServerSideProps(ctx) {
  // do something
  return {
    // data
  };
}
Run Code Online (Sandbox Code Playgroud)

然后在每个页面(是的,每个页面,我找不到解决方法;如果您不需要在服务器页面上执行代码,它甚至可能会有所帮助),执行以下操作:

import getServerSideProps from "../lib/serverProps";

// other stuff...

export { getServerSideProps };
Run Code Online (Sandbox Code Playgroud)

或者

// other stuff...

export { default as getServerSideProps } from "../lib/serverProps";
Run Code Online (Sandbox Code Playgroud)

如果您想添加其他代码以在getServerSideProps特定页面内运行,您可以按照以下方式执行某些操作...

import serverProps from "../lib/serverProps";

// other stuff...

export async function getServerSideProps(ctx) {
  // do custom page stuff...
  return {
    ...await serverProps(ctx),
    ...{
      // pretend this is what you put inside
      // the return block regularly, e.g.
      props: { junk: 347 }
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

  • 此方法帮助我非常轻松地从服务器端集成 **protected** 和 **auth** 路由。谢谢。将此标记为有用。 (4认同)

dmu*_*dro 5

getServerSideProps在 中不起作用_app.js。请参阅文档

您可以getInitialProps在您的自定义应用程序组件中使用旧的,但随后自动静态优化被禁用,这是 Next.js 押注的重中之重。

可能值得深入研究您的 cookie 用例并弄清楚您是否真的需要在服务器端阅读它。

  • 谢谢(你的)信息!尽管在所有页面上提供一些用户数据似乎很常见,但您将如何在 nextjs 中解决这个问题?谢谢你! (15认同)
  • 对此有什么解决办法吗?我非常需要它。 (6认同)