簡體   English   中英

在客戶端 React 中添加 ld+json 腳本標簽

[英]Add ld+json script tag in client-side React

我目前已經構建了一個 React 應用程序。 因為它是一個 SPA,所以它只有一個 index.html 文件。 我想添加 2 個“ld+json” script標簽,即用於特定路線的評論和書簽。

我已在該組件的componentDidMount中注入了script標記,但 Google 結構化數據測試工具沒有讀取該標記。

是因為 Google 直接從 index.html 讀取,並且因為我的script標簽捆綁在 main.js 中,所以無法讀取嗎?

是否可以在客戶端 React 中執行此操作? 服務器端渲染是唯一可行的方法嗎?

-- 詳細說明--- 我目前想實現一個像IMDB這樣的系統,即每當我們在goole中搜索電影時; IMDB 搜索結果將在谷歌頁面本身中顯示電影的評級。 為此,我需要在 index.html 文件中放置一個腳本

<script type='application/ld+json'>
  {
      "@context": "http://schema.org/",
      "@type": "Review",
      "itemReviewed": {
        "@type": "Thing",
        "name": "Name"
      },
      "reviewRating": {
        "@type": "Rating",
        "ratingValue": "3",
        "bestRating": "5"
      },
      "publisher": {
        "@type": "Organization",
        "name": "1234"
      }
    }
</script>

由於我的應用程序是一個 SPA,我不能把它放在我的主 index.html 文件中。

我目前的方法:假設“/movies/inception”路由呈現“MovieDetail”組件。 所以,我目前正在這個組件的末尾添加腳本。

import React from 'react';
import JsonLd from '../path_to_JSONLD';

class MovieDetail extends React.Component {
 render(){
 let data = {
  "@context": "http://schema.org/",
  "@type": "Review",
  "itemReviewed": {
    "@type": "Thing",
    "name": "Name"
   },
    "reviewRating": {
     "@type": "Rating",
     "ratingValue": "3",
     "bestRating": "5"
    },
   "publisher": {
     "@type": "Organization",
     "name": "1234"
    }
  }
   return(
    <SOME COMPOENTS />
    <JsonLd data={data} />

 )
}

我的 JsonLd 組件

import React from 'react';

const JsonLd = ({ data }) =>
  <script
    type="application/ld+json"
    dangerouslySetInnerHTML={{ __html: JSON.stringify(data) }}
  />;

  export default JsonLd;

所以,當我檢查組件時; 我可以看到動態添加的腳本標簽。 但是,在結構測試工具“ https://search.google.com/structured-data/testing-tool ”中。 驗證后不顯示架構。 因此,我問是否可以通過客戶端完成,或者 SSR 只是解決方案,我可以提供更新的 index.html 作為響應。

我希望這能消除混亂。 謝謝!

對我來說, React Helmet效果很好。

<Helmet>
    <script className='structured-data-list' type="application/ld+json">{structuredJSON}</script>
</Helmet> 

其中structuredJSON JSON類似於此類函數的結果:

export const structuredDataSingle = (prod, imgPath, availability) => {

    let data = {
        "@context": "http://schema.org/",
        "@type": "Product",
        "name": `${prod.title}`,
        "image": prod.images.map((item) => imgPath + item),
        "description": prod['description'],
        "url": location.href,
        "offers": {
            "@type": "Offer",
            "priceCurrency": `${prod['currency'] || "₴"}`,
            "price": prod['price'] ? `${parseFloat(prod['price'])}` : 0,
            "availability": `${availability}`,
            "seller": {
                "@type": "Organization",
                "name": "TopMotoPro"
            }
        }
    };

    // brand
    if(prod['brand']) {
        data['mpn'] = prod['brand'];
        data['brand'] = {
            "@type": "Thing",
            "name": `${prod['brand']}`
        };
    }

    // logo
    if(prod['logo']){
        data['logo'] = imgPath + prod['logo'];
    }

    return JSON.stringify(data);
};

你可以簡單地危險地渲染它

<script type='application/ld+json' dangerouslySetInnerHTML={ { __html: `{ "@context": "http://schema.org", "@type": "LocalBusiness", ... }`}} />

解決方案:使用“react-meta-tags”鏈接: https : //github.com/s-yadav/react-meta-tags

import React from 'react';
import MetaTags from 'react-meta-tags';
import JsonLd from 'path_to_jsonld';


export default class MetaComponent extends React.Component {
  render() {
   return (
    <div className="wrapper">
      <MetaTags>
        <title>{this.props.title}</title>
        <meta property="og:type" content="website" />
        <meta name="description" content={this.props.description} />
        <meta name="og:description" content={this.props.description} />
        <meta property="og:title" content={this.props.title} />
        <meta property="og:url" content={window.location.href} />
        <meta property="og:site_name" content={"content"} 
         />
        {
          this.props.jsonLd && 
            <JsonLd data={this.props.jsonLd} />
        }
      </MetaTags>
    </div>
  )
 }
}

然后我在我的主要組件中導入了這個組件

import React from 'react';
import MetaComponent from '../path_to_Metacomponent';

class MovieDetail extends React.Component {
 render(){
let data = {
  "@context": "http://schema.org/",
  "@type": "Review",
  "itemReviewed": {
    "@type": "Thing",
    "name": "Name"
    },
"reviewRating": {
    "@type": "Rating",
    "ratingValue": "3",
    "bestRating": "5"
   },
 "publisher": {
   "@type": "Organization",
   "name": "1234"
  }
}
   return(
    <SOME COMPOENTS />
    <MetaComponent jsonLd={data} title={"abcd"} description={"xyza"} />

 )
}

該包的作用是將腳本標簽動態插入到 head 標簽中,並且由於腳本現在沒有捆綁在 main.js 文件中,谷歌可以從源代碼中讀取它。

正如@Дмитрий Дорогонов 所建議的那樣,您可以使用React Helmet來內聯腳本元素。 您還可以將它們內聯並使用變量插值:

<script type="application/ld+json">{`
  {
    "@context": "http://schema.org",
    "@type": "${typeVariable}"
  }
`}</script>

這幫助了我:

  1. 准備您的 JSON 並將其字符串化。
const ORG_SCHEMA = JSON.stringify({
  "@context": "http://schema.org",
  "@type": "Organization",
  "name": "Allround",
  "description": "Allround - An online learning experience through creative and co-curricular pursuits for kids aged 5-15. Learn western vocals, keyboard, chess & Spanish from experts.",
  "url": "https://allround.club/",
  "logo": "https://allround.club/favicon.svg",
  "address": {
      "@type": "PostalAddress",
      "streetAddress": "DD3, Diamond District, HAL Old Airport Road",
      "addressLocality": "Bengaluru",
      "addressRegion": "Karnataka",
      "postalCode": "560008",
      "Telephone": "+918035003600"
  },
  "sameAs": [
      "https://www.facebook.com/Allround-Learning",
      "https://www.linkedin.com/company/allround-club",
      "https://www.instagram.com/allround.club/"
  ]
});
  1. 使用dangerouslySetInnerHTML設置字符串化JSON在腳本標簽。
<script type='application/ld+json' dangerouslySetInnerHTML={ { __html: ORG_SCHEMA} } />

您可以在此處查看它如何顯示給爬蟲: https : //allround.club/

您可以使用 Google 的 react-schemaorg:

https://github.com/google/react-schemaorg

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM