Mar*_*re 3 javascript typescript reactjs next.js
我是 Next.js 的新手,我很难将数据从 _document 传递到 _app。
我需要将路径名服务器端从_document.ts
to传递_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()],
};
Run Code Online (Sandbox Code Playgroud)
_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();
}, []);
Run Code Online (Sandbox Code Playgroud)
当我console.log(pageProps)
只得到eg时{ locale: 'en' }
,没有pathname
从_document.ts传递的属性。
你知道我如何将道具从 _document 传递到 _app
我遇到了这个问题,我使用 req 对象将我的参数从 _app 发送到 _document。基于 NextJs 解析顺序,我们可以使用 req (IncomingMessage) 对象。NextJs 在服务器端的解析顺序:
在客户端:
示例 (TS):我将一个名为 Direction 的属性从 _app 的 getInitialProps 函数发送到 _document。
(ctx.req as any).direction = organization.direction;
Run Code Online (Sandbox Code Playgroud)
在 _document 的 getInitialProps 中:
const direction = ctx.req.direction;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4216 次 |
最近记录: |