React Helmet在</html>外部添加<script type =“ application / ld + json”>

时间:2019-12-11 21:25:19

标签: reactjs widget frontend react-helmet

我已经在我的网站上实现了第三方小部件,以获取Rich Snippets明星。问题是Google-bot和Google结构化数据测试工具无法识别ld + json标记,因为它在 html 标记之外。我曾使用React Helmet将脚本强行放入 head 标签内,但徒劳!

enter image description here

这是我的应用程序的代码:

return (
        <div className="cleanslate widget-box">
            {comp}
            <Helmet>
                <script type="application/ld+json">
                {`
                    {
                        "@context": "https://schema.org/",
                        "@type": "CreativeWorkSeries",
                        "name": "${this.state.name}",
                        "aggregateRating": {
                            "@type": "AggregateRating",
                            "ratingValue": "${this.state.rating}",
                            "bestRating": "10",
                            "ratingCount": "${this.state.voters}"
                        }
                    }
                `}
                </script>
            </Helmet>
        </div>
    )

1 个答案:

答案 0 :(得分:1)

在json上尝试JSON.stringify()。像这样:

const ldJson = {
  "@context": "https://schema.org",
  "@type": "BreadcrumbList",
  "itemListElement": [{
    "@type": "ListItem",
    "position": 1,
    "name": "Blogs",
    "item": "https://www.speblog.org"
  },{
    "@type": "ListItem",
    "position": 2,
    "name": head.title,
    "item": window.location.href
  }]
};

<script type="application/ld+json">
  {JSON.stringify(ldJson)}
</script>

直到我这样做(react-helment@^5.2.1),我才为我工作