【问题标题】:how to use <Head> with nextJS如何在 nextJS 中使用 <Head>
【发布时间】:2019-07-18 06:49:33
【问题描述】:

我在将移动元标记导入 nextJS 应用程序时遇到问题。 根据此处的文档,这应该可以 https://nextjs.org/docs#populating-head

但我没有看到标题或我自己的任何元属性被渲染。 我看到的是:

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

这看起来像是某种默认值。

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

帮助表示赞赏!

【问题讨论】:

    标签: meta next.js html-head


    【解决方案1】:

    我无法重现此问题。自编写此问题以来,可能修复了一个错误,但documentation 确实指出他们使用key 属性来帮助 Next.js 跟踪元标记并在它们出现在父元素和子元素中时消除重复。

    为避免head 中出现重复标签,您可以使用key 属性, 这将确保标签只呈现一次,如 下面的例子:

    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
    

    【讨论】:

      【解决方案2】:

      NextJS 的 &lt;Head&gt; 组件似乎有点问题。

      一方面,在不同组件中设置的两个&lt;Head&gt; 标签有时会以非常奇怪的方式相互干扰。另一方面,有时将它放在页面组件中有效,有时则无效。而且规则似乎完全随机。

      唯一对我有用的是在_document.js 中使用&lt;Head&gt;。 :/

      【讨论】:

      • 请注意,不再支持在_document.js 中使用&lt;Head&gt;。有一个明确的警告可以避免它,如果你需要设置全局标签,你应该在_app.js 中使用它。
      • 也许使用key='xyz' 属性。这强制在标题中仅添加一次给定标签。
      猜你喜欢
      • 2019-11-25
      • 2022-11-11
      • 2021-04-20
      • 1970-01-01
      • 2022-12-09
      • 2021-10-03
      • 2021-08-10
      • 2021-11-03
      • 2021-09-17
      相关资源
      最近更新 更多