NextJS Head组件呈现陈旧的道具

时间:2018-10-15 13:27:44

标签: javascript reactjs next.js ssr

我的目标是尝试将此标签放在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返回第一个值,然后在客户端返回空值,使其返回到location.host + router.asPath

唯一的问题是,无论何时router.asPath更新,它似乎都比实际值落后一步。例如,假设我在“ http://bla.com/two”上,而我的前一页是“ http://bla.com/one”,则链接将显示为<link rel="canonical" href="http://bla.com/one" />

我希望我在这里已经对自己做了足够的解释,希望有人对您有帮助:)

1 个答案:

答案 0 :(得分:1)

如果它在渲染中,那么如果您想了解为什么router.asPath shows previous URL的原因,请使用location.href而不是location.host + router.asPath