我如何在 nextjs 中使用 application/ld+json

Ely*_*edy 12 reactjs next.js

我在 next js 中有一个 Layout 并且我使用 Head 组件。我想使用模式 json 但我有一个错误。

这是我的代码:

<Head>
        <script type="application/ld+json">
          {{
            "@context": "http://schema.org",
            "@type": "Person",
            address: {
              "@type": "PostalAddress",
              addressLocality: "Seattle",
              addressRegion: "WA",
              postalCode: "98052",
              streetAddress: "20341 Whitworth Institute 405 N. Whitworth"
            },
            colleague: [
              "http://www.xyz.edu/students/alicejones.html",
              "http://www.xyz.edu/students/bobsmith.html"
            ],
            email: "mailto:jane-doe@xyz.edu",
            image: "janedoe.jpg",
            jobTitle: "Professor",
            name: "Jane Doe",
            telephone: "(425) 123-4567",
            url: "http://www.janedoe.com"
          }}
        </script>
</Head>
Run Code Online (Sandbox Code Playgroud)

这是我的错误:

Objects are not valid as a React child (found: object with keys {@context, @type, address, colleague, email, image, jobTitle, name, telephone, url}). 

If you meant to render a collection of children, use an array instead. in script (at Layout.js:130) in head in Head (at _document.js:43) in html in Html (at _document.js:42) in MyDocument in Context.Provider in Context.Provider
Run Code Online (Sandbox Code Playgroud)

请帮忙!

fel*_*osh 19

You need to use dangerouslySetInnerHTML in order to put your schema data.

<Head>
  <script
    type="application/ld+json"
    dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData) }}
  />
</Head>
Run Code Online (Sandbox Code Playgroud)

  • 请注意,在上面的示例中您仍然需要“JSON.stringify”。 (2认同)
  • @TimeParadox 取决于您的 html 来自哪里。如果是第 3 方,是的。如果它只是来自您的一大块数据,则不会。 (2认同)

YHR*_*YHR 12

const addJsonLd = () => {
  return {
    __html: `
     YOUR JSON OBJECT HERE
    `
  }
}

<Head>
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={addJsonLd()}
      key="item-jsonld"
    />
</Head>
Run Code Online (Sandbox Code Playgroud)

NextJS 文档中提到了该方法。在 NextJS 应用程序中设置元数据


小智 11

实际上现在建议使用 Next.js Script 组件 next/script

import Script from "next/script";

<Head>
    <Script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonData) }}
    />
</Head>
Run Code Online (Sandbox Code Playgroud)

  • 执行此操作时出现错误:next/script 组件不应在 next/head 组件中使用。 (2认同)