【问题标题】:How do I solve a var.map is not a function TypeError?如何解决 var.map is not a function TypeError?
【发布时间】:2021-08-12 20:02:44
【问题描述】:

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

以下代码 sn-p 给了我一个 服务器错误,上面写着 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 实例本身的代码或某些依赖问题有关?如果有人可以帮助我,我将不胜感激。谢谢。

【问题讨论】:

  • 无论你在哪里&lt;BlogPage posts={thisIsNotAnArray} /&gt;,检查你传递给这个组件的对象。
  • 如果BlogPage 是页面组件,那么该页面的数据获取方法在哪里?您如何/在哪里获取 posts 的数据?

标签: javascript typescript next.js typeerror strapi


【解决方案1】:

首先对帖子进行控制台并检查它是未定义、为空还是帖子类型必须是数组

我认为你应该尝试关注

posts.posts.map()

【讨论】:

  • 抱歉这个愚蠢的问题,但我应该把“console.log(posts)”放在哪里?我不认为 sintax 是这里的问题,因为我按照你所说的做了,但没有用
  • 在你的源代码中尝试上面的 return 语句。
  • 它不起作用,因为页面没有正确加载并出现错误
  • 好的,在任何你调用 BlogPage 组件的地方进行控制台,并确保别名 var 必须是 posts={some_array}
猜你喜欢
  • 2021-06-22
  • 2018-09-01
  • 2018-11-14
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多