首页 > 解决方案 > 如何解决 var.map is not a function TypeError?

问题描述

我正在为我的网站开发一个博客页面,该页面基于 Next.js,使用 TypeScript 编写,并使用 Strapi 作为 CMS API。

下面的代码片段给了我一个服务器错误TypeError: posts.map is not a function我不知道为什么。

type BlogPageProps = {
  posts: PostData[];
};

const BlogPage = ({ posts }: BlogPageProps) => {
  useEffect(() => {
    AOS.init({ duration: 700 });
  }, []);

  return (
    <>
      <SEO title={`Blog | ${SITE_NAME}`} />

      <AnimationContainer animation="appearFromAbove">
        {posts.map((post) => (
          <PostCard effect="fade-up" key={post.id} post={post} />
        ))}
      </AnimationContainer>
    </>
  );
};

export default BlogPage;

PostData[] 只是一种由以下参数组成的类型:

export type PostData = {
  id: PostID;
  title: string;
  content: string;
  slug: string;
  author: PostAuthor;
  category: PostCategory;
  created_by: PostCreatedBy;
  updated_by: PostCreatedBy;
  created_at: string;
  updated_at: string;
  cover: PostCover;
};

我认为这与 API 实例本身的代码或某些依赖问题有关?如果有人可以帮助我,我将不胜感激。谢谢你。

标签: javascripttypescriptnext.jstypeerrorstrapi

解决方案


首先控制台帖子并检查它是否未定义,null,或者帖子类型必须是数组

我认为你应该尝试关注

post.posts.map()


推荐阅读