Next.JS动态 meta标签

ugmeyewa  于 2023-06-05  发布在  其他
关注(0)|答案(1)|浏览(510)

我在我的next.js应用程序中为一个页面添加了一些动态 meta标签。

import CoinTossPage from '@/views/CoinTossPage';
import React, { useEffect, useState } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import axios from 'axios';

function CoinTossComponent() {
  const router = useRouter();
  const { id } = router.query;
  const [poolData, setPoolData] = useState(null);

  useEffect(() => {
    if (id) {
      fetchPoolData();
    }
  }, [id]);

  // fetch pool data from API using pool id
  const fetchPoolData = async () => {
    try {
      let config = {
        method: 'get',
        url: `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/gambling/coin-flip/pool/${id}`,
        headers: {
          Authorization: `Bearer ${process.env.NEXT_PUBLIC_API_KEY}`,
        },
      };
      const response = await axios(config);
      if (response.status === 200) {
        const payload = response.data.payload;
        if (payload) {
          setPoolData(payload);
        } else {
          setPoolData(null);
        }
      }
    } catch (error) {
      console.log('ERROR while fetching active pools from API ', error);
    }
  };

  return (
    <>
      <Head>
        <meta property="og:title" content={poolData?.tokenSymbol} />
        <meta property="og:image" content={poolData?.imageUrl} />
      </Head>
      <CoinTossPage />
    </>
  );
}

export default CoinTossComponent;

这是它是如何添加的,这是它如何出现时,我看它在页面检查。

它清楚地显示了 meta标签中的动态内容。但是当我分享页面链接时,此图像未显示。

问题是什么?
我试着阅读他们的文档https://nextjs.org/learn/seo/rendering-and-ranking/metadata,并根据它添加了 meta标签。

7qhs6swi

7qhs6swi1#

感谢所有帮助我解决上述问题的人。这是正确的代码

import CoinTossPage from '@/views/CoinTossPage';
import React from 'react';
import Head from 'next/head';
import axios from 'axios';

function CoinTossComponent({poolData}) {
  return (
    <>
      <Head>
        <meta property="og:title" content={poolData?.tokenSymbol} />
        <meta property="og:image" content={poolData?.imageUrl} />
      </Head>
      <CoinTossPage />
    </>
  );
}

export async function getServerSideProps(context) {

  const { id } = context.query; // Access the route parameter

  let config = {
    method: 'get',
    url: `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/gambling/coin-flip/pool/${id}`,
    headers: {
      Authorization: `Bearer ${process.env.NEXT_PUBLIC_API_KEY}`,
    },
  };
  const response = await axios(config);
  const poolData = response.data.payload;

  // Return the data as props
  return {
    props: {
      poolData,
    },
  };
}

export default CoinTossComponent;

相关问题