TypeError: fields.map is not a function when doing next dynamic sitemap with next-sitemap

huangapple go评论78阅读模式
英文:

TypeError: fields.map is not a function when doing next dynamic sitemap with next-sitemap

问题

我遇到的错误是"field.map is not a function"。我不知道为什么会发生这种情况。有人可以帮我解决吗?

英文:

I am trying to do dynamic sitemap for my site and here is my code:

import { GetServerSideProps } from 'next';
import { getServerSideSitemap, ISitemapField } from 'next-sitemap';
import { makeSlugFromString } from '../../lib/helpers';
import { BaseNCategories } from '../../lib/generalConstants';

export const getServerSideProps = async (ctx: any) => {
  const response = await fetch('http://baseapi/v3/category-list');
  const categoriesData = await response.json();
  const categories: any[] = categoriesData.cat;
  const categoryBn = BaseNCategories.filter((baseCategory) => {
    return categories.some((category) => category.CategoryID === baseCategory.CategoryID);
  });
  const fields: ISitemapField[] = categoryBn.map((category) => ({
    loc: `baseApi/${makeSlugFromString(category.Slag)}`,
    lastmod: new Date().toISOString(),
    // priority: 0.7,
    // changefreq: 'daily',
  }));
  console.log({ fields });
  return getServerSideSitemap(ctx, fields);
};

export default function Site() {}

The error I'm getting is "field.map is not a function". I don't know why this is happening. Can anyone help me fix this?

答案1

得分: 1

categoryBn不是一个数组
由于categoryBn是通过使用过滤函数从BaseNCategories派生出来的,所以它应该始终是一个数组。然而,为了确保,您可以在创建字段数组之前添加一个检查,以确保categoryBn确实是一个数组。

将这个代码段替换为:

if (!Array.isArray(categoryBn)) {
  console.error('categoryBn不是一个数组:', categoryBn);
  return { notFound: true }; // 根据需要返回404页或错误页。
}

const fields: ISitemapField[] = categoryBn.map((category) => ({
  loc: `baseApi/${makeSlugFromString(category.Slag)}`,
  lastmod: new Date().toISOString(),
}));

请注意,我保留了代码中的JavaScript部分,并只翻译了注释和错误消息。

英文:

categoryBn is not an array
Since categoryBn is derived from BaseNCategories using the filter function, it should always be an array. However, to be certain, you can add a check before creating the fields array to ensure categoryBn is indeed an array.

Replace this:

    const fields: ISitemapField[] = categoryBn.map((category) => ({
  loc: `baseApi/${makeSlugFromString(category.Slag)}`,
  lastmod: new Date().toISOString(),
}));

With this:

    if (!Array.isArray(categoryBn)) {
  console.error('categoryBn is not an array:', categoryBn);
  return { notFound: true }; // Return a 404 page or an error page as needed.
}

const fields: ISitemapField[] = categoryBn.map((category) => ({
  loc: `baseApi/${makeSlugFromString(category.Slag)}`,
  lastmod: new Date().toISOString(),
}));

huangapple
  • 本文由 发表于 2023年7月20日 15:07:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76727438.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定