slugs.map 不是生成动态站点地图时的函数错误

slugs.map is not a function error when generating dynamic sitemap

我想根据我的 slugs 路径生成一个动态站点地图。我使用 next-sitemap 库:https://github.com/iamvishnusankar/next-sitemap.

当我想输入http://localhost:3000/server-sitemap.xml时出现错误 slugs.map is not a function../pages/server-site.xml/index.js.

next-sitemap.config.js

module.exports = {
  siteUrl: "https://mywebsite.vercel.app/",
  changefreq: "daily",
  priority: 0.7,
  //   sitemapSize: 5000,
  generateRobotsTxt: true,
  exclude: ["/server-sitemap.xml"],

  robotsTxtOptions: {
    policies: [
      {
        userAgent: "*",
        allow: "/",
      },
    ],
    additionalSitemaps: [
      "https://mywebsite.vercel.app/server-sitemap.xml",
    ],
  },
};

../pages/server-site.xml/index.js

import { getServerSideSitemap } from "next-sitemap";
import { getPortfolioSlugs } from "../../lib/data";

export const getServerSideProps = async (ctx) => {
  // Method to source urls from cms
  const slugs = await getPortfolioSlugs();

  const fields = slugs.map((slug) => ({
    loc: `https://mywebsite.vercel.app/portfolio/${slug.slug}`,
    lastmod: new Date().toISOString(),
  }));

  return getServerSideSitemap(ctx, fields);
};

export default function Sitemap() {}

GraphQL 请求:

import { GraphQLClient, gql } from "graphql-request";
const endpoint = process.env.REACT_APP_GRAPHCMS_API;

export const getPortfolioSlugs = async () => {
  const graphQLClient = new GraphQLClient(endpoint);

  const query = gql`
    {
      portfolios {
        slug
      }
    }
  `;
  return await graphQLClient.request(query);
};

GraphCMS API 游乐场 getPortfolioSlugs() 查询 returns:

{
  "data": {
    "portfolios": [
      {
        "slug": "kostka-brukowa-test"
      },
      {
        "slug": "kostka-cypryjska"
      },
      {
        "slug": "granito"
      },
      {
        "slug": "carmino"
      },
      {
        "slug": "test-xxx"
      }
    ]
  }
}

PortfolioList,我console.log(slugs)来自这个道具

// (...)
export const getServerSideProps = async () => { 
  const slugs = await getPortfolioSlugs(); 
  return { props: { slugs: slugs.portfolios, }, }; 
}; 

const PortfolioList = ({slugs }) => {
  console.log(slugs);
return (
//(...)
)}
// (...)

GraphQL 查询返回的数据是一个对象,因此当您尝试在 slugs 上调用它时,有关 .map 不是函数的错误。

您要映射的数组应该可以在 slugs.portfolios 下访问。

// /pages/server-site.xml/index.js
export const getServerSideProps = async (ctx) => {
    const slugs = await getPortfolioSlugs();
    // Change following line
    const fields = slugs.portfolios.map((slug) => ({
        loc: `https://mywebsite.vercel.app/portfolio/${slug.slug}`,
        lastmod: new Date().toISOString(),
    }));

    return getServerSideSitemap(ctx, fields);
};