gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:37:43 26 4
gpt4 key购买 nike

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

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

例如<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' } , 没有 pathname从 _document.ts 传递的属性。

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

最佳答案

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

  1. app.getInitialProps
  2. page.getInitialProps
  3. document.getInitialProps
  4. app.render
  5. 页面渲染
  6. 文档.render

在客户端:

  1. app.getInitialProps
  2. page.getInitialProps
  3. app.render
  4. 页面渲染

示例 (TS):我将一个名为 direction 的属性从 _app 的 getInitialProps 函数发送到 _document。

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

在 _document 的 getInitialProps 中:

const direction = ctx.req.direction;

关于javascript - 如何在 Next.js 中将路径名从 _document 传递到 _app,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62711476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com