meta标签动态值,例如图像,标题,描述未在reactjs的head标签中更新

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

我想在reactjs中为图片,标题和说明设置动态值这就是我所做的

import { useEffect, useState, useRef } from 'react';
const [thumbnail, setThumbnail] = useState('')
const [metaTitle, setMetaTitle] = useState('');
useEffect(() => {
    const run1 = async () => {
      const x = await apis.getVendorDetails({category, region, brandName});
      setVendorData(x.data)
      if(thisVendor == '') thisVendor = vendorData;
    }
    run1();
  }, [])
if(vendorData !=='' && vendorData !== undefined && (facebook == '' && instagram == '' && website == '' && metaTitle == '' && thumbnail == '')){
    setThumbnail(vendorData.allImages !== undefined || vendorData.allImages !== '' ? vendorData.allImages[0] : '')
    setMetaTitle((vendorData.category !== undefined || vendorData.category !== '') ? vendorData.category + ' | ' + vendorData.companyName : '');
  }

return (
        <Layout1 vendorData={vendorData} isLogin={isLogin} customerData={customerData} isLoginCustomer={isLoginCustomer}>
          <Head>
            <meta property="og:title" content={metaTitle}/>
            <meta property="og:image" itemProp="image" content={thumbnail}/>
            <meta property="og:type" content="website"/>
            <meta property="og:image:width" content="256"/>
            <meta property="og:image:height" content="256"/>
          </Head>
</Layou1>
);

这是我尝试过的

图像和标题中内容的元值未更新请帮助我enter image description here

reactjs image title meta-tags use-state
1个回答
0
投票

考虑使用React Helmet

import { useEffect, useState, useRef } from "react";
import { Helmet } from "react-helmet";

const [thumbnail, setThumbnail] = useState("");
const [metaTitle, setMetaTitle] = useState("");

useEffect(() => {
  const run1 = async () => {
    const x = await apis.getVendorDetails({ category, region, brandName });
    setVendorData(x.data);
    if (thisVendor == "") thisVendor = vendorData;
  };
  run1();
}, []);

if (
  vendorData !== "" &&
  vendorData !== undefined &&
  facebook == "" &&
  instagram == "" &&
  website == "" &&
  metaTitle == "" &&
  thumbnail == ""
) {
  setThumbnail(
    vendorData.allImages !== undefined || vendorData.allImages !== ""
      ? vendorData.allImages[0]
      : ""
  );
  setMetaTitle(
    vendorData.category !== undefined || vendorData.category !== ""
      ? vendorData.category + " | " + vendorData.companyName
      : ""
  );
}

return (
  <Layout1
    vendorData={vendorData}
    isLogin={isLogin}
    customerData={customerData}
    isLoginCustomer={isLoginCustomer}
  >
    <Helmet>
      <meta property="og:title" content={metaTitle} />
      <meta property="og:image" itemProp="image" content={thumbnail} />
      <meta property="og:type" content="website" />
      <meta property="og:image:width" content="256" />
      <meta property="og:image:height" content="256" />
    </Helmet>
  </Layout1>
);
© www.soinside.com 2019 - 2024. All rights reserved.