how to use <Head> with nextJS

谁都会走 提交于 2020-05-31 03:50:32

问题


I'm having problems getting mobile metatags into a nextJS app. According to the docs here, this should work https://nextjs.org/docs#populating-head

But I don't see the title or any of my own meta properties getting rendered. All I see is:

<!DOCTYPE html><html><head><meta charSet="utf-8" class="next-head"/>

which looks like some type of default.

import Link from 'next/link'
import Head from 'next/head'
import Header from '../components/Header'
import BaseLayout from '../components/BaseLayout.js'

const Index = () => (
  <BaseLayout>
    <Head>
      <title>HSK App</title>
      <meta name="viewport" content="initial-scale=1.0, width=device-width" />
    </Head>
    <Link href='/quizList'>
      <h3>HSK Quiz App!</h3>
    </Link>
  </BaseLayout>
)
export default Index

Help appreciated!


回答1:


NextJS's <Head> component seems a bit buggy.

For one thing, two <Head> tags set in different components sometimes will interfere with each other in really bizarre ways. For another, sometimes having it in page components works, sometimes it doesn't. And the rules seems perfectly random.

The only thing that consistently worked for me is using <Head> in _document.js. :/




回答2:


I can't reproduce this problem. Maybe a bug was fixed since this question was written, but the documentation does point out they use a key attribute to help Next.js keep track of meta tags and eliminate duplicates when they appear in parent and child elements.

To avoid duplicate tags in your head you can use the key property, which will make sure the tag is only rendered once, as in the following example:

import Head from 'next/head'

function IndexPage() {
  return (
    <div>
      <Head>
        <title>My page title</title>
        <meta property="og:title" content="My page title" key="title" />
      </Head>
      <Head>
        <meta property="og:title" content="My new title" key="title" />
      </Head>
      <p>Hello world!</p>
    </div>
  )
}

export default IndexPage


来源:https://stackoverflow.com/questions/54856503/how-to-use-head-with-nextjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!