You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript+Next.js类型错误:ReactElement缺少必填posts属性

问题排查与修复

错误原因分析

  1. 组件返回类型定义错误:你把IndexPage组件的返回类型指定为InferGetStaticPropsType<typeof getStaticProps>,这个类型是用来描述组件接收的props的,而组件本身应该返回React元素类型(React.ReactElement或JSX.Element)。TypeScript因此误判组件需要返回包含posts属性的对象,但实际返回的是JSX元素,触发类型不匹配错误。
  2. map循环未返回元素:postList.map内部的代码块没有return语句,导致循环后没有生成任何JSX元素,同时也会引发类型警告。
  3. 组件标签未闭合:<Post>组件的标签没有正确闭合,存在语法错误。

修复后的完整代码

import React, { useState } from "react";
import { InferGetStaticPropsType } from "next";
import Post from "../components/Post";
import { IPost } from "../types";

const API_URL: string = 'https://jsonplaceholder.typicode.com/posts'

// 正确定义组件props类型,返回类型为React.ReactElement
export default function IndexPage(
  { posts }: InferGetStaticPropsType<typeof getStaticProps>
): React.ReactElement {
  const [postList, setPostList] = useState(posts);

  if (!postList) {
    return <h1>Loading....</h1>
  } 

  return (
    <div>
      <h1>My posts</h1>
      {postList.map((post: IPost) => {
        // 添加return返回JSX元素
        return (
          <div key={post.id}>
            <h1>post{post.id}</h1>
            {/* 闭合Post组件标签 */}
            <Post post={post} />
          </div>
        )
      })}
    </div>
  )
}

export async function getStaticProps() {
  const res = await fetch(API_URL)
  const posts: IPost[] = await res.json()

  return {
    props: {
      posts
    }
  }
}

额外优化点

  • 把setpostList改为驼峰命名setPostList,符合React/TypeScript的命名规范。
  • 把key属性移到map循环生成的最外层div上,避免同一个元素重复设置key。

内容的提问来源于stack exchange,提问作者risky last

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:06:28