- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 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解析顺序:
在客户端:
示例 (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/
我是一名优秀的程序员,十分优秀!