当渲染服务器端(无getInitialProps)时,如何访问_app中的_app中的next.js上下文数据?

发布于 2025-02-13 22:10:14 字数 609 浏览 0 评论 0原文

我正在从_app.js文件中删除getInitialProps,并且需要能够在渲染服务器端或客户端。为此,我需要在_app组件中访问下一个。我该如何访问它?

const getAcceptLanguageString = (): string => {
  let req: IncomingMessage | undefined;
  if (!isClientSide()) {
    return req?.headers['accept-language'] ?? 'en-US';
  }
  return window.__NEXT_DATA__?.props?.acceptLanguage ?? '';
};

const MyApp = ({
  Component,
  apolloClient,
  router,
}) => {
  const acceptLanguage = getAcceptLanguageString();
  // Do something with `acceptLanguage`

  return <Component />;
};

I am removing getInitialProps from the _app.js file and need to be able to get the user's accept-language either when rendering server-side or client-side. In order to do that I need to have access to the Next.js context in the _app component. How can I get access to that?

const getAcceptLanguageString = (): string => {
  let req: IncomingMessage | undefined;
  if (!isClientSide()) {
    return req?.headers['accept-language'] ?? 'en-US';
  }
  return window.__NEXT_DATA__?.props?.acceptLanguage ?? '';
};

const MyApp = ({
  Component,
  apolloClient,
  router,
}) => {
  const acceptLanguage = getAcceptLanguageString();
  // Do something with `acceptLanguage`

  return <Component />;
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文