繁体   English   中英

如何在 Next.js 中将路径名从 _document 传递到 _app

[英]How to pass pathname from _document to _app in Next.js

我是 Next.js 的新手,我很难将数据从 _document 传递到 _app。

我需要将路径名服务器端从_document.ts_app.ts ,然后传递到App组件中,以便我可以在Head元素服务器端注入自定义标签。 每个页面都会有特定的链接。

例如<link rel="x-default" hrefLang="x-default" href="https://example.com/about-us">

将在页面https://example.com/about-us上。

当前的实现如下所示:

_document.tx 中的 getInitialProps

    const sheets = new ServerStyleSheets();
    const originalRenderPage = ctx.renderPage;

    ctx.renderPage = () =>
      originalRenderPage({
        enhanceApp: (App) => (props) => sheets.collect(<App {...props} />),
      });
    const { lang } = ctx.query;
    const initialProps = await Document.getInitialProps(ctx);

    return {
      ...initialProps,
      pathname: ctx.asPath,
      locale: getLocaleFromLanguage(lang as SupportedLanguages),
      styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()],
    };

_app.ts 的一部分

function App({ Component, pageProps }) {
  console.log(pageProps)
  let { locale } = pageProps;
  if (!locale) {
    locale = DEFAULT_LOCALE;
  }

  useEffect(() => {
    // Remove the server-side injected CSS.
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles) {
      jssStyles.parentElement.removeChild(jssStyles);
    }
    smoothscroll.polyfill();
  }, []);

当我console.log(pageProps)我只得到例如{ locale: 'en' }时,_document.ts 没有传递pathname属性。

你知道如何将道具从 _document 传递到 _app

我遇到了这个问题,我使用 req object 将我的参数从 _app 发送到 _document。 根据 NextJs 解析顺序,我们可以使用 req (IncomingMessage) object。 服务器端NextJs解析顺序:

  1. app.getInitialProps
  2. page.getInitialProps
  3. document.getInitialProps
  4. app.render
  5. page.render
  6. 文档.render

在客户端:

  1. app.getInitialProps
  2. page.getInitialProps
  3. app.render
  4. page.render

示例 (TS):我从 _app 的 getInitialProps function 向 _document 发送了一个名为 direction 的属性。

(ctx.req as any).direction = organization.direction;

在 _document 的 getInitialProps 中:

const direction = ctx.req.direction;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM