我正在使用 next.js 的应用程序路由器。 我想为两个页面“/blog”和“/blog/[searchKeyword]”添加 jsonLd 数据。 但我在这个过程中遇到了一些问题。
博客 > 布局.tsx
return (
<>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
id="jsonLd-blog"
/>
{children}
</> );
博客/[搜索关键字] > 布局.tsx
return ( <>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
id={jsonLd-${params.searchKeyword}}
/>
{children}
</> );
"use client";
import { useEffect } from "react";
const RemoveJsonScript: React.FC<{ elementId: string }> = ({ elementId }) => {
useEffect(() => {
const oldJsonLds = document.getElementById(elementId);
if (oldJsonLds) {
oldJsonLds.remove();
}
}, []);
return <></>;
};
export default RemoveJsonScript;
3.第三,然而,它触发了下面的错误,无论它是在服务器组件还是客户端组件中使用..
Uncaught NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
4.此外,它不适用于“next/head”中的 标签,而仅适用于 标签。这个问题与上述三个问题无关,但我想知道为什么会这样。
我不知道如何解决这个问题。 Next.js 是我用过的最好的 SEO 框架,但是这个错误让我很沮丧..我需要你的帮助。
我想摆脱父级的 jsonLd 脚本标记,而不出现任何错误消息,例如“Uncaught NotFoundError: Failed toexecute 'removeChild' on 'Node': The Node to be returned is not a child of this node.”
此行为是预期的,因为
layout.tsx
将包装其所有子布局或页面。因此,如果您有 /blog/layout.tsx
和 /blog/[searchKeyword]/layout.tsx
,则 /blog/[searchKeyword]/page.tsx
的组件树将如下所示:
<BlogLayout>
<BlogSearchKeywordLayout>
<BlogSearchKeywordPage />
</BlogSearchKeywordLayout>
</BlogLayout>
最适合您的解决方案是将 json-ld 脚本标签放在
/blog/page.tsx
和 /blog/[searchKeyword]/page.tsx
中