Next.js添加SEO Schema时报Objects are not valid as a React child错误求助
解决方案
错误原因
你直接将JSON对象作为子元素放入了<script>标签内,React不支持直接渲染对象类型的子元素,因此触发了Objects are not valid as a React child报错。
修复方案
方案1:JSON.stringify包裹数据
直接把你的schema结构化对象用JSON.stringify()转为字符串后再放入标签即可,修改后的代码如下:
<Head> <title>随机颜色项目</title> <meta name="description" content="随机颜色工具可根据你的点击生成随机颜色,每次点击按钮都会生成一个新的随机色" /> {/* 其余代码 */} {/* 搜索引擎SEO结构化代码 */} <script type="application/ld+json"> {JSON.stringify({ "@context": "https://schema.org", "@type": "WebSite", image: ["https://avatars2.githubusercontent.com/u/32416397"], author: { "@type": "Person", name: "Rajdeep Singh" }, // 其余schema配置 })} </script> </Head>
方案2:使用dangerouslySetInnerHTML属性
也可以通过React内置的dangerouslySetInnerHTML属性注入结构化数据,写法如下:
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify({ "@context": "https://schema.org", "@type": "WebSite", image: ["https://avatars2.githubusercontent.com/u/32416397"], author: { "@type": "Person", name: "Rajdeep Singh" }, // 其余schema配置 }) }} />
Next.js 13+ App Router额外方案
如果你使用的是Next.js 13及以上版本的App Router模式,可以直接在页面/布局的metadata配置中定义结构化数据,不需要手动编写script标签:
// app/page.js 或者 app/layout.js export const metadata = { title: '随机颜色项目', description: '随机颜色工具可根据你的点击生成随机颜色,每次点击按钮都会生成一个新的随机色', jsonLd: { "@context": "https://schema.org", "@type": "WebSite", image: ["https://avatars2.githubusercontent.com/u/32416397"], author: { "@type": "Person", name: "Rajdeep Singh" }, // 其余schema配置 } }
内容的提问来源于stack exchange,提问作者officialrajdeepsingh
相关产品推荐
相关产品推荐

