【发布时间】:2018-10-15 13:27:43
【问题描述】:
我的目标是尝试将此标签放在我的 NextJS 应用程序的头部:
<link rel="canonical" href="http://stackoverflow.com" />
我已经设置了一个自定义 _app.js,并在 getInitialProps 中使用 url 包返回我的 URL。这工作正常,我在页面加载时获得了 url。这是这个的代码:
static async getInitialProps({ Component, ctx }) {
const initialProps = {};
if (isServer) {
const { req: { url: pageUrl, headers: { host } } } = ctx;
initialProps.canonicalHref =
createUrl({subdomain: host.split('.')[0], pathname: url.parse(pageUrl).pathname});
}
return { ...initialProps }
}
在我的渲染函数中,我使用它来渲染链接标签:
<Head>
<link rel="canonical" href={canonicalHref || location.host + router.asPath} key="canonical" />
</Head>
想法是 getInitialProps 返回第一个值,然后在客户端返回 null,使其回退到 location.host + router.asPath。
唯一的问题是 router.asPath 在更新时似乎比实际值落后一步。例如,如果我在“http://bla.com/two”上,而我的上一页是“http://bla.com/one”,那么链接将呈现为<link rel="canonical" href="http://bla.com/one" />。
我希望我在这里解释得足够好,我希望有人有任何想法可以提供帮助:)
【问题讨论】:
标签: javascript reactjs next.js server-side-rendering