[英]Property '0' is missing in type 'any[]' but required in type '[{ id: string; gp: boolean; }]
[英]Property '...' is missing in type 'ReactElement<any, any>' but required in type '{...}'
我是 TypeScript 的新手,我正在尝试通过使用以下代码从getStaticProps
获取数据来呈现页面:
import React, {FormEvent, useState} from "react";
import { InferGetStaticPropsType } from "next";
import AddPost from '../components/AddPost';
import Post from "../components/Post";
import { IPost } from "../types";
const API_URL: string = 'https://jsonplaceholder.typicode.com/posts'
export default function IndexPage ( {
posts
}) : InferGetStaticPropsType<typeof getStaticProps> {
const [postList, setpostList] = useState(posts);
if(!postList) {
return <h1>Loadin....</h1>
}
return (
<div>
<h1>My posts</h1>
{postList.map((post : IPost) => {
<div>
<h1>post{post.id}</h1>
<Post key={post.id} post={post}
</div>
})}
</div>
)
}
export async function getStaticProps() {
const res = await fetch(API_URL)
const posts : IPost[] = await res.json()
return {
props: {
posts
}
}
}
我的帖子类型定义为:
export interface IPost {
id: number
title: string
body: string
}
代码执行良好,但在尝试返回 jsx 以在屏幕上呈现时出现 ts 错误:
Property 'posts' is missing in type 'ReactElement<any, any>' but required in type '{ posts: IPost[]; }'.
你能帮我解决这里有什么问题吗?
您似乎输入错误。 我建议您使用 React 中的FC
键入IndexPage
,因为该页面是一个 React 功能组件,如下所示:
import { FC } from "react";
const IndexPage: FC<{ posts: IPost[] | null }> = ({ posts }) => {
return <div></div>;
};
export default IndexPage;
此外,您的map
部分也不正确,因为您没有返回任何内容,也没有添加key
:
{postList.map((post: IPost) => {
return (
<div key={post.id}>
<h1>post{post.id}</h1>
<Post key={post.id} post={post}
</div>
);
})}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.