如何删除子组件layout.tsx中父组件的script标签?

问题描述 投票:0回答:1

我正在使用 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}
</> );
  1. 首先,在页面“/blog/[searchKeyword]”中,它不仅有来自其layout.tsx的jsonLd,还有来自“/blog”的layout.tsx。
  2. 其次,我尝试使用“remove()”方法及其 id 来删除父 jsonld 脚本代码,例如下面的“jsonLd-blog”。
"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.”

next.js json-ld app-router
1个回答
0
投票

此行为是预期的,因为

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

© www.soinside.com 2019 - 2024. All rights reserved.